|
| 1 | +package com.thealgorithms.slidingwindow; |
| 2 | + |
| 3 | +/** |
| 4 | + * The Longest Subarray with Sum Less Than or Equal to k algorithm finds the length |
| 5 | + * of the longest subarray whose sum is less than or equal to a given value k. |
| 6 | + * |
| 7 | + * <p> |
| 8 | + * Worst-case performance O(n) |
| 9 | + * Best-case performance O(n) |
| 10 | + * Average performance O(n) |
| 11 | + * Worst-case space complexity O(1) |
| 12 | + * |
| 13 | + * @author https://github.com/Chiefpatwal |
| 14 | + */ |
| 15 | +public final class LongestSubarrayWithSumLessOrEqualToK { |
| 16 | + |
| 17 | + // Prevent instantiation |
| 18 | + private LongestSubarrayWithSumLessOrEqualToK() { |
| 19 | + } |
| 20 | + |
| 21 | + /** |
| 22 | + * This method finds the length of the longest subarray with a sum less than or equal to k. |
| 23 | + * |
| 24 | + * @param arr is the input array |
| 25 | + * @param k is the maximum sum allowed |
| 26 | + * @return the length of the longest subarray with sum less than or equal to k |
| 27 | + */ |
| 28 | + 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 |
| 40 | + } |
| 41 | + |
| 42 | + // Update maxLength if the current window is valid |
| 43 | + maxLength = Math.max(maxLength, right - left + 1); |
| 44 | + } |
| 45 | + |
| 46 | + return maxLength; // Return the maximum length found |
| 47 | + } |
| 48 | +} |
0 commit comments