- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSubarraySum.java
More file actions
Latest commit
24 lines (22 loc) · 670 Bytes
/
Copy pathSubarraySum.java
File metadata and controls
24 lines (22 loc) · 670 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// O(n) time solution
classSubarraySum {
publicintmaxSubArrayLen(int[] nums, intk) {
if (nums == null || nums.length == 0) {
return0;
}
Map<Integer, Integer> map = newHashMap<>();
intlen = 0;
intsum = 0;
map.put(0, -1); // eliminates the need to check sum == k
for (inti = 0; i < nums.length; i++) {
sum += nums[i];
if (map.containsKey(sum - k)) {
len = Math.max(len, i - map.get(sum - k));
}
if (!map.containsKey(sum)) {
map.put(sum, i);
}
}
returnlen;
}
}