然后就查找能用至多k个元素填充使连续串最长的区间[i,l]
扫描字符串中的每个位置i,计算k有能力填充的以i为起点的最长的区间[i,l]的长度
如果对于每个位置i,在找区间[i,l]时用for循环遍历的话肯定会超时,采用二分查找将复杂度降到nlog(n)
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn = 100000;
char s[maxn + 10];
int a[maxn + 1], b[maxn + 10];
int n, k;
bool check(int l, int r) {
if (a[r] - a[l - 1] <= k || b[r] - b[l - 1] <= k) {
return true;
}
return false;
}
int main()
{
cin >> n >> k;
scanf("%s", s + 1);
for (int i = 1; i <= n; i++) {
a[i] = a[i - 1] + (s[i] == 'a');
b[i] = b[i - 1] + (s[i] == 'b');
}
int ans = -1;
for (int i = 1; i <= n; i++) {
int l = i, r = n;
while (l <= r) {
int mid = (l + r) >> 1;
check(i, mid) ? l = mid + 1 : r = mid - 1;
}
ans = max(ans, r - i + 1);
}
cout << ans << endl;
return 0;
}