Source Code
#include<bits/stdc++.h>
using namespace std;

typedef long long ll;
#define int ll


#define lp3(i,s,n) for(int i = s;i < int(n); ++i)
#define lp(i, n) lp3(i,0,n)
#define pb push_back
#define debug(x) cout<<"[" << #x << " is: " << x << "] "<<endl;

#define file freopen("input.in","r",stdin);
#define fastIO std::ios::sync_with_stdio(false); cin.tie(0);


void solve(){
    int n; cin>>n;
    string s; cin>>s;
    if(s[0] == s.back()){
        cout<<n-1<<endl;
    }
    else{
        vector<int> x, y;
        lp(i, n)
            if(s[i] == s[0])
                x.push_back(i);
            else
                y.push_back(i);

        int ans = n;
        for(int k: x){
            int indx = lower_bound(y.begin(), y.end(), k) - y.begin();
            if(indx == n)
                continue;
            ans = min(ans, y[indx]-k+1);
        }
        cout<<n-ans<<endl;
    }
}

int32_t main() {  fastIO
    
    int t = 1; //cin>>t;
    while(t--){
        solve();
    }
    
    return 0;
}
Copy
Pop Pop Logic
GNU G++17
4 ms
1.8 MB
Accepted