Untitled
public class MaxLengthSubarray { public int maxLengthSubarray(int[] nums, int k) { int i = 0; // Start of the window int j = 0; // End of the window int sum = 0; int maxLength = 0; while (j < nums.length) { sum += nums[j]; // Add the current element to the window // Shrink the window until the sum is <= k while (sum > k) { sum -= nums[i]; i++; } // single shrink only for maxlen if (sum > k) { sum -= nums[i]; i++; } if(sum <= k) maxLength = Math.max(maxLength, j - i + 1); // Move the end pointer j++; } return maxLength; } }
Leave a Comment