class Solution {
public:
int findMaxLength(vector<int>& nums) {
int n = nums.size();
vector<int> s(n + 1);
for(int i = 1; i <= n; i++) {
s[i] = s[i - 1] + (nums[i - 1] == 1 ? 1 : -1);
}
unordered_map<int, int> mp;
mp[0] = 0;
int res = 0;
for(int i = 1; i <= n; i++) {
if(mp.count(s[i])) {
res = max(res, i - mp[s[i]]);
} else {
mp[s[i]] = i;
}
}
return res;
}
};