思路:枚举结尾,然后暴力二分就好了,用前缀和预处理一下,那么前缀和之差,就是你需要改变的个数
#include<bits\stdc++.h>
using namespace std;
const int maxn = 1e5+7;
int n,k;
int sum[maxn];
char s[maxn];
int main()
{
scanf("%d%d",&n,&k);
scanf("%s",s+1);
for(int i = 1;i<=n;i++)
{
sum[i]=sum[i-1];
if(s[i]=='a')
sum[i]++;
}
int ans = 0;
for(int i = 1;i<=n;i++)
{
int l=1,r=i,res=i;
while(l<=r)
{
int m = (l+r)>>1;
if(sum[i]-sum[m-1] <= k)
r=m-1,res=m;
else
l=m+1;
}
if(sum[i]-sum[res-1]<=k)
ans = max(ans,i-res+1);
}
for(int i = 1;i<=n;i++)
{
sum[i]=sum[i-1];
if(s[i]=='b')
sum[i]++;
}
for(int i = 1;i<=n;i++)
{
int l = 1,r=i,res=i;
while(l<=r)
{
int m = (l+r)>>1;
if(sum[i]-sum[m-1]<=k)
r=m-1,res=m;
else
l=m+1;
}
if(sum[i]-sum[res-1]<=k)
ans = max(ans,i-res+1);
}
printf("%d\n",ans);
}