Poison

325. Maximum Size Subarray Sum Equals k

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Solution {
public int maxSubArrayLen(int[] nums, int k) {
int preSum = 0, maxLength = 0;
Map<Integer, Integer> preSumToEndIndexMap = new HashMap<>((int) (nums.length / 0.75));
preSumToEndIndexMap.put(0, -1);
for (int i = 0; i < nums.length; i++) {
preSum += nums[i];
preSumToEndIndexMap.putIfAbsent(preSum, i);

Integer index = preSumToEndIndexMap.get(preSum - k);
if (index != null) {
maxLength = Math.max(maxLength, i - index);
}
}

return maxLength;
}
}
Reference

325. Maximum Size Subarray Sum Equals k