-
Notifications
You must be signed in to change notification settings - Fork 67
Expand file tree
/
Copy pathContiguousArray.java
More file actions
41 lines (27 loc) · 791 Bytes
/
ContiguousArray.java
File metadata and controls
41 lines (27 loc) · 791 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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
/*
Source: https://leetcode.com/problems/contiguous-array/
Time: O(n), where n is the size of the given array(nums)
Space: O(n), map is required to store the indexes for each unique sum
*/
class Solution {
public int findMaxLength(int[] nums) {
Map<Integer, Integer> map = new HashMap<>();
map.put(0, -1);
int sum = 0;
int maxLen = 0;
int len = nums.length;
for(int i = 0; i < len; ++i) {
sum += (nums[i] == 1) ? 1 : -1;
Integer firstOccurredIndexWithSumVal = map.get(sum);
if(firstOccurredIndexWithSumVal != null) {
int subArrayLen = i - firstOccurredIndexWithSumVal;
if(subArrayLen > maxLen) {
maxLen = subArrayLen;
}
} else {
map.put(sum, i);
}
}
return maxLen;
}
}