-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathLC_525_ContiguousArrayZeroOne.cpp
50 lines (41 loc) · 1.17 KB
/
LC_525_ContiguousArrayZeroOne.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
50
/*
https://leetcode.com/problems/contiguous-array/
525. Contiguous Array
https://practice.geeksforgeeks.org/problems/largest-subarray-of-0s-and-1s/1/
*/class Solution {
public:
int findMaxLength(vector<int>& nums) {
int sum = 0;
int max_len = 0;
// BruteForce
/*
for(int i=0; i<nums.size(); i++)
{
sum = (nums[i]==0)? -1: 1;
for(int j=i+1; j<nums.size(); j++)
{
sum += (nums[j]==0)?-1 : 1;
if(sum == 0 && max_len < j-i+1)
{
max_len = j-i+1;
}
}
}
*/
//using hashmap
unordered_map<int,int> prefix;
prefix[0]=-1;
for(int i=0; i<nums.size(); i++)
{
sum += (nums[i]==0)? -1: 1;
if(prefix.find(sum) != prefix.end())
{
if(max_len < i - prefix[sum])
max_len = i-prefix[sum];
}
else
prefix[sum] = i;
}
return max_len;
}//end
};