Untitled

mail@pastecode.io avatar
unknown
c_cpp
21 days ago
1.7 kB
4
Indexable
Never
void solve(int tc)
{   
    int n;
    cin >> n;
    vector<int> a(n);
    int ph;
    bool all_zero = true, all_one = true;
    for (int i = 0; i < n; i++){
        cin >> ph;
        if (ph == 1){a[i] = -1; all_zero = false;}
        else {a[i] = 1; all_one = false;}
    }
    if (all_one){
        cout << n - 1 << "\n";
        return;
    }
    else if (all_zero){
        cout << n << "\n";
        return;
    }
    int mx = 0;
    int sum = 0;
    vector<pair<pair<int, int>, int>> tracker;
    int start_index = 0;
    for (int i = 0; i < n; i++){
        sum += a[i];
        mx = max(mx, sum);
        if (sum < 0){
            tracker.push_back({{start_index, i}, sum -= a[i]});
            start_index = i + 1;
            sum = 0;
        }
        else {
            tracker.push_back({{start_index, i}, sum});
        }
    }
    int end_index;
    for (auto elem: tracker){
        if (elem.second == mx){
            start_index = elem.first.first;
            end_index = elem.first.second;
            break;
        }
    }
    int ans = 0;
    for (int i = 0; i < n; i++){
        if (i < start_index && a[i] == -1) ans++;
        else if (i > end_index && a[i] == -1) ans++;
        else if (start_index <= i && i <= end_index){
            if (a[i] == 1) ans++;
        }
    }
    cout << ans << "\n";
}


 
int main()
{
    cin.tie(NULL);
    ios_base::sync_with_stdio(false);
    // freopen("breedflip.in", "r", stdin);
    // freopen("breedflip.out", "w", stdout);
    // preprocess();
    // int t;
    // cin >> t;
    // for(int i = 1; i <= t; i++)
    solve(1);
    return 0;
}
Leave a Comment