fork(1) download
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3. #define int long long int
  4. #define double long double
  5. inline int power(int a, int b) {
  6. int x = 1;
  7. while (b) {
  8. if (b & 1) x *= a;
  9. a *= a;
  10. b >>= 1;
  11. }
  12. return x;
  13. }
  14.  
  15.  
  16. const int M = 1000000007;
  17. const int N = 3e5+9;
  18. const int INF = 2e9+1;
  19. const int LINF = 2000000000000000001;
  20.  
  21. //_ ***************************** START Below *******************************
  22.  
  23.  
  24. //* Start with valid window
  25.  
  26. void consistency(string str, int k) {
  27. int n = str.size();
  28.  
  29. int ans = 0;
  30.  
  31.  
  32. int s = 0, e = 0;
  33. deque<char> up, down;
  34.  
  35. while(e<n){
  36. while(!up.empty() && str[up.back()] > str[e] ) up.pop_back();
  37. up.push_back(e);
  38.  
  39. while(!down.empty() && str[down.back()] < str[e] ) down.pop_back();
  40. down.push_back(e);
  41.  
  42. //* Invalid window => Shrink it (untill it becomes valid)
  43. while(s<=e){
  44. int mini = (str[up.front()] - 'a');
  45. int maxi = (str[down.front()] - 'a');
  46. if(maxi - mini <= k ){
  47. break;
  48. }
  49.  
  50. if(up.front() == s) up.pop_front();
  51. if(down.front() == s) down.pop_front();
  52. s++;
  53. }
  54.  
  55. int len = e-s+1;
  56. ans = max(ans, len);
  57.  
  58. e++;
  59. }
  60.  
  61. cout << ans << endl;
  62.  
  63. }
  64.  
  65.  
  66. void solve() {
  67.  
  68. int k;
  69. cin >> k;
  70.  
  71. string str;
  72. cin >> str;
  73.  
  74. consistency(str, k);
  75.  
  76. }
  77.  
  78.  
  79.  
  80.  
  81.  
  82. int32_t main() {
  83. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  84.  
  85. int t = 1;
  86. // cin >> t;
  87. while (t--) {
  88. solve();
  89. }
  90.  
  91. return 0;
  92. }
Success #stdin #stdout 0s 5316KB
stdin
2
abccabcdabdabd
stdout
7