-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathContiguous_Array.cpp
More file actions
36 lines (35 loc) · 901 Bytes
/
Contiguous_Array.cpp
File metadata and controls
36 lines (35 loc) · 901 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
#include "vector"
#include "map"
#include "Cmath"
#include "algorithm"
using namespace std;
class Solution {
public:
int findMaxLength(vector<int>& nums) {
unordered_map<int, int> count;
int n = nums.size();
int sum = 0;
if (n == 1) {
return 0;
}
int answer = 0;
int tempAnswer;
for (int i=0; i<n; i++) {
if (nums[i] == 1) {
sum += 1;
} else {
sum += -1;
}
if (count.find(sum) != count.end()) {
tempAnswer = i - (count.find(sum)->second);
answer = max(tempAnswer, answer);
} else if (sum == 0) {
tempAnswer = i+1;
answer = max(tempAnswer, answer);
}else {
count.insert({sum, i});
}
}
return answer;
}
};