High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotes beauty of the string as the maximum length of a substring (consecutive subsequence) consisting of equal letters.
Vasya can change no more than k characters of the original string. What is the maximum beauty of the string he can achieve?
The first line of the input contains two integers n and k (1 ≤ n ≤ 100 000, 0 ≤ k ≤ n) — the length of the string and the maximum number of characters to change.
The second line contains the string, consisting of letters 'a' and 'b' only.
Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.
4 2 abba
4
8 1 aabaabaa
5
In the first sample, Vasya can obtain both strings "aaaa" and "bbbb".
In the second sample, the optimal answer is obtained with the string "aaaaabaa" or with the string "aabaaaaa".
题解:用两个指针,i=j=1,保持它们之间的a个数是k,算出最大值,初始化(i,j)然后保持它们之间b个数是k,算出最大值。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <map>
#include <stack>
using namespace std;
char a[100005];
int fa[100005],fb[100005];
int main()
{
int n,k;
cin>>n>>k;
getchar();
for(int i=1;i<=n;i++)
{
scanf("%c",&a[i]);
fb[i]=fb[i-1]+(a[i]=='b');
fa[i]=fa[i-1]+(a[i]=='a');
}
int left=1,right=1,ans=0;
do
{
while(fb[right+1]-fb[left-1]<=k&&right<n)
right++;
ans=max(ans,right-left+1);
left++;
}while(right<n);
left=right=1;
do
{
while(fa[right+1]-fa[left-1]<=k&&right<n)
right++;
ans=max(ans,right-left+1);
left++;
}while(right<n);
cout<<ans<<endl;
}