Skip to content

Commit 84164df

Browse files
added new method
1 parent 6085b1f commit 84164df

File tree

2 files changed

+19
-18
lines changed

2 files changed

+19
-18
lines changed

src/main/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToK.java

Lines changed: 17 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -26,23 +26,23 @@ private LongestSubarrayWithSumLessOrEqualToK() {
2626
* @return the length of the longest subarray with sum less than or equal to k
2727
*/
2828
public static int longestSubarrayWithSumLEK(int[] arr, int k) {
29-
int maxLength = 0; // To store the maximum length found
30-
int currentSum = 0; // To store the current sum of the window
31-
int left = 0; // Left index of the sliding window
32-
33-
for (int right = 0; right < arr.length; right++) {
34-
currentSum += arr[right]; // Expand the window to the right
35-
36-
// Shrink the window from the left if the current sum exceeds k
37-
while (currentSum > k && left <= right) {
38-
currentSum -= arr[left]; // Remove the leftmost element
39-
left++; // Move the left index to the right
29+
int length = 0 ;
30+
int currSum = 0 ;
31+
int maxLength = Integer.MIN_VALUE;
32+
// inspired by kadane's algorithm
33+
for (int i = 0 ; i<arr.length;i++){
34+
currSum = currSum + arr[i];
35+
length++;
36+
if(currSum==k){
37+
maxLength = Math.max(maxLength, length);
38+
length = 0 ;
39+
currSum = 0 ;
40+
}if(i==arr.length-1){
41+
currSum=0;
42+
length=0;
4043
}
41-
42-
// Update maxLength if the current window is valid
43-
maxLength = Math.max(maxLength, right - left + 1);
44+
4445
}
45-
46-
return maxLength; // Return the maximum length found
47-
}
46+
return maxLength ;
47+
}
4848
}

src/test/java/com/thealgorithms/slidingwindow/LongestSubarrayWithSumLessOrEqualToKTest.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,10 +13,11 @@ public class LongestSubarrayWithSumLessOrEqualToKTest {
1313
* Tests for the longest subarray with a sum less than or equal to k.
1414
*/
1515
@Test
16-
public void testLongestSubarrayWithSumLEK() {
16+
public static void testLongestSubarrayWithSumLEK() {
1717
assertEquals(3, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {1, 2, 3, 4}, 6)); // {1, 2, 3}
1818
assertEquals(4, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {1, 2, 3, 4}, 10)); // {1, 2, 3, 4}
1919
assertEquals(2, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {5, 1, 2, 3}, 5)); // {5}
2020
assertEquals(0, LongestSubarrayWithSumLessOrEqualToK.longestSubarrayWithSumLEK(new int[] {1, 2, 3}, 0)); // No valid subarray
2121
}
22+
2223
}

0 commit comments

Comments
 (0)