fork 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. deque<int> up, down;
  31.  
  32. int s = 0 , e = 0;
  33.  
  34. while(e<n){
  35. while(!up.empty() && str[e] < str[up.front()]) up.pop_front();
  36. up.push_back(e);
  37.  
  38. while(!down.empty() && str[e] > str[down.front()]) down.pop_front();
  39. down.push_back(e);
  40.  
  41. while(s<=e){
  42. int maxi = str[down.front()];
  43. int mini = str[up.front()];
  44.  
  45. if(maxi - mini <= k) break;
  46.  
  47. if(up.front() == s) up.pop_front();
  48. if(down.front() == s) down.pop_front();
  49. s++;
  50. }
  51.  
  52. ans = max(ans, e-s+1);
  53. e++;
  54.  
  55. }
  56.  
  57. cout << ans << endl;
  58.  
  59. }
  60.  
  61.  
  62. void solve() {
  63.  
  64. int k;
  65. cin >> k;
  66.  
  67. string str;
  68. cin >> str;
  69.  
  70. consistency(str, k);
  71.  
  72. }
  73.  
  74.  
  75.  
  76.  
  77.  
  78. int32_t main() {
  79. ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
  80.  
  81. int t = 1;
  82. // cin >> t;
  83. while (t--) {
  84. solve();
  85. }
  86.  
  87. return 0;
  88. }
Success #stdin #stdout 0s 5320KB
stdin
2
abccabcdabdabd
stdout
7