Skip to content

Instantly share code, notes, and snippets.

@nguyyentantai
Last active April 15, 2020 03:43
Show Gist options
  • Save nguyyentantai/b44e2f2853c9a0803f0adf306fe1421e to your computer and use it in GitHub Desktop.
Save nguyyentantai/b44e2f2853c9a0803f0adf306fe1421e to your computer and use it in GitHub Desktop.
Solution Contiguous Array Leetcode
class Solution {
public:
int findMaxLength(vector<int>& nums) {
int maxSize = 0, count = 0, size = nums.size(), count0 = 0;
for(const auto n: nums)
if(!n) ++count0;
vector<int> m(size + 1, -2); // Use -2 to mean uninitialized
m[count0] = -1;
for(int i = 0; i < size; ++i) {
count += nums[i] == 0 ? -1 : 1;
const int d = count0 + count;
if(m[d] != -2) {
maxSize = max(maxSize, i - m[d]);
}
else m[d] = i;
}
return maxSize;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment