-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathContiguous Array.cpp
49 lines (39 loc) · 1.11 KB
/
Contiguous Array.cpp
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
42
43
44
45
46
47
48
49
class Solution {
public:
struct temp{
int first, last;
};
int findMaxLength(vector<int>& nums) {
int n = nums.size(), sum = 0, ans = 0;
map<int, temp> m;
for(int i = 0; i < n; i++){
if(nums[i] == 0){
sum--;
}
else{
sum++;
}
if(m.find(sum) == m.end()){
temp t;
t.first = i;
t.last = i;
m[sum] = t;
}
else{
m[sum].last = i;
}
}
map<int, temp> :: iterator it = m.begin();
while(it != m.end()){
int currSum = it->first, first = (it->second).first, last = (it->second).last;
if(currSum == 0){
ans = max(ans, last + 1);
}
else{
ans = max(ans, max(m[currSum].last - first, last - m[currSum].first));
}
it++;
}
return ans;
}
};