public class Solution {
public int maxSubArrayLen(int[] nums, int k) {
if (nums == null || nums.length < 1) return 0;
int len = nums.length;
int[] prefixSum = new int[len + 1];
for (int i = 1; i <= len; i++) {
prefixSum[i] = nums[i - 1] + prefixSum[i - 1];
}
Map<Integer, Integer> map = new HashMap<>();
map.put(0, 0);
int res = 0;
for (int i = 1; i <= len; i++) {
if (map.containsKey(prefixSum[i] - k)) {
res = Math.max(res, i - map.get(prefixSum[i] - k));
}
if (!map.containsKey(prefixSum[i])) // keep only 1st duplicate as we want first index as left as possible
map.put(prefixSum[i], i);
}
return res;
}
}