Skip to content

Commit 828e811

Browse files
Create Day 26 Contiguous Array.cpp
1 parent ef736e1 commit 828e811

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed

Day 26 Contiguous Array.cpp

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
PROBLEM:
2+
3+
4+
5+
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
6+
7+
Example 1:
8+
Input: [0,1]
9+
Output: 2
10+
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
11+
Example 2:
12+
Input: [0,1,0]
13+
Output: 2
14+
Explanation: [0, 1] (or [1, 0]) is a longest contiguous subarray with equal number of 0 and 1.
15+
16+
17+
18+
19+
SOLUTION:
20+
21+
22+
23+
class Solution {
24+
public:
25+
int findMaxLength(vector<int>& nums) {
26+
27+
int i,n,ans=0,sum=0;
28+
n=nums.size();
29+
unordered_map<int,int> m;
30+
31+
m[0]=-1;
32+
for(i=0;i<n;i++)
33+
{
34+
if(nums[i]==0)
35+
sum--;
36+
else
37+
sum++;
38+
39+
if(m.find(sum)!=m.end())
40+
ans=max(ans,i-m[sum]);
41+
else
42+
m[sum]=i;
43+
}
44+
45+
return ans;
46+
47+
}
48+
};

0 commit comments

Comments
 (0)