educative.io

Cant we use the same Sliding window pattern to find the maxSubArrayLen with the given sum?

I kind off used the same pattern as used to find the min len subarray with given sum to get the max len subarray with given sum.

Question : Given an array nums and a target value k, find the maximum length of a subarray that sums to k.
public int maxSubArrayLen(int[] nums, int k) {
int maxLen = Integer.MIN_VALUE;
int windowStart = 0;
int sum = 0;
for(int windowEnd =0 ; windowEnd < nums.length; windowEnd++){
sum = sum+nums[windowEnd];
if(sum >= k){
maxLen = Math.max(maxLen, windowEnd-windowStart+1);
sum = sum-nums[windowStart];
windowStart++;
}
}
return maxLen;
}

It fails in this scenario
[-2,-1,2,1]
1

Any help ??