fork download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5.  
  6.  
  7. const int M = 1000000007;
  8. const int N = 3e5+9;
  9. const int INF = 2e9+1;
  10. const int MAXN = 100000;
  11. const int LINF = 2000000000000000001;
  12.  
  13. //_ ***************************** START Below *******************************
  14.  
  15.  
  16.  
  17.  
  18. string a;
  19.  
  20. int consistency(int n, int k){
  21. int ans = 0;
  22.  
  23. int act = 0;
  24. int bct = 0;
  25. int pairs = 0;
  26.  
  27. int s = 0, e = 0;
  28.  
  29. while(e<n){
  30. if(a[e] == 'a') act++;
  31. else if(a[e] == 'b') bct++;
  32.  
  33. if(a[e] == 'b') pairs += act;
  34.  
  35. if(pairs <= k){
  36. ans = max(ans, e-s+1);
  37. e++;
  38. }
  39. else{
  40. while(s<=e && pairs > k){
  41. if(a[s] == 'a') act--;
  42. else if(a[s] == 'b') bct--;
  43.  
  44. if(a[s] == 'a') pairs -= bct;
  45. s++;
  46. }
  47. ans = max(ans, e-s+1);
  48. e++;
  49. }
  50. }
  51.  
  52. return ans;
  53.  
  54. }
  55.  
  56.  
  57.  
  58.  
  59.  
  60.  
  61.  
  62.  
  63.  
  64. void solve() {
  65.  
  66. int n, k;
  67. cin >> n >> k;
  68. cin >> a;
  69. cout << consistency(n, k) << endl;
  70.  
  71.  
  72.  
  73.  
  74. }
  75.  
  76.  
  77.  
  78.  
  79.  
  80. int32_t main() {
  81. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  82.  
  83. int t = 1;
  84. while (t--) {
  85. solve();
  86. }
  87.  
  88. return 0;
  89. }
Success #stdin #stdout 0s 5320KB
stdin
6 2
aabcbb
stdout
4