[LeetCode] Contiguous Array

525. Contiguous Array

Given a binary array nums, return the maximum length of a contiguous subarray with an equal number of 0 and 1.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Solution {
public:
int findMaxLength(vector<int>& nums) {
unordered_map<int, int> m;
int diff = 0, res = 0;
m[0] = -1;
for(int i = 0; i < nums.size(); i++) {
diff += (nums[i] ? 1 : -1);
if(m.count(diff)) {
res = max(res, i - m[diff]);
} else m[diff] = i;
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/02/04/PS/LeetCode/contiguous-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.