题目展示
代码演示
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
//因为要考虑 1 和 -1 抵消的情况,所以数组前面要弄一个0占位!
int main() {
int n;
cin >> n;
vector<int> a(n), b(n+1,0);
for(int i=0; i<n; ++i){
cin >> a[i];
a[i] = (a[i] == 0 )? -1 : 1;
}
for(int i=1; i<=n; ++i){
b[i] = a[i-1] + b[i-1];
}
unordered_map<int, int> mp;
int maxlen = 0;
for(int i=0; i<=n; ++i){
if(mp.find(b[i]) == mp.end()){
mp[b[i]] = i;
}else{
maxlen = max(maxlen, i - mp[b[i]]);
}
}
cout << maxlen << endl;
return 0;
}