fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. int solve_for(char king, const string &s){
  5. int n = s.size();
  6. vector<int> pref(n+1, 0);
  7.  
  8. for(int i = 1; i <= n; i++){
  9. if(s[i-1] == king) pref[i] = pref[i-1] + 1;
  10. else pref[i] = pref[i-1] - 1;
  11. }
  12.  
  13. stack<int> st;
  14. for(int i = 0; i <= n; i++){
  15. if(st.empty() || pref[i] < pref[st.top()])
  16. st.push(i);
  17. }
  18.  
  19. int ans = 0;
  20. for(int r = n; r >= 0; r--){
  21. while(!st.empty() && pref[r] > pref[st.top()]){
  22. ans = max(ans, r - st.top());
  23. st.pop();
  24. }
  25. }
  26. return ans;
  27. }
  28.  
  29. int main(){
  30. ios::sync_with_stdio(false);
  31. cin.tie(nullptr);
  32.  
  33. int n;
  34. cin >> n;
  35. string s;
  36. cin >> s;
  37.  
  38. int ans = 0;
  39. ans = max(ans, solve_for('a', s));
  40. ans = max(ans, solve_for('b', s));
  41. ans = max(ans, solve_for('c', s));
  42.  
  43. cout << ans << '\n';
  44. }
  45.  
Success #stdin #stdout 0.01s 5296KB
stdin
6
abcacc
stdout
5