-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path24_contiguous-array.cpp
More file actions
39 lines (28 loc) · 848 Bytes
/
24_contiguous-array.cpp
File metadata and controls
39 lines (28 loc) · 848 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
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int n = nums.size();
unordered_map<int, int> mp;
// vector<int> prefix(n, 0);
// for(int i=0; i<n; i++) if(nums[i] == 0) nums[i] = -1;
// prefix[0] = nums[0];
// for(int i=1; i<n; i++){
// prefix[i] = prefix[i-1] + nums[i];
// }
// for(int i:prefix) cout << i << " ";
// cout << endl;
int sum = 0;
int maxLen = 0;
mp[0] = -1;
for(int i=0; i<n; i++){
if(nums[i] == 0) nums[i] = -1;
sum += nums[i];
if(mp.find(sum) != mp.end()) {
maxLen = max(maxLen, i - mp[sum]);
} else {
mp[sum] = i; // store first occurrence only
}
}
return maxLen;
}
};