High school student Vasya got a string of length n as a birthday present. This string consists of letters 'a' and 'b' only. Vasya denotesbeauty 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".
#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
#include<ctype.h>
#include<math.h>
#include<set>
#include<map>
#include<vector>
#include<queue>
#include<bitset>
#include<algorithm>
#include<time.h>
using namespace std;
void fre() { freopen("c://test//input.in", "r", stdin); freopen("c://test//output.out", "w", stdout); }
#define MS(x,y) memset(x,y,sizeof(x))
#define MC(x,y) memcpy(x,y,sizeof(x))
#define MP(x,y) make_pair(x,y)
#define ls o<<1
#define rs o<<1|1
typedef long long LL;
typedef unsigned long long UL;
typedef unsigned int UI;
template <class T1, class T2>inline void gmax(T1 &a, T2 b) { if (b>a)a = b; }
template <class T1, class T2>inline void gmin(T1 &a, T2 b) { if (b<a)a = b; }
const int N = 1e5 + 10, M = 0, Z = 1e9 + 7, ms63 = 0x3f3f3f3f;
int n, k;
char s[N];
int a[N], b[N];
bool check(int l, int r)
{
return a[r] - a[l - 1] <= k || b[r] - b[l - 1] <= k;
}
int main()
{
while (~scanf("%d%d%s", &n, &k, s + 1))
{
int n = strlen(s + 1);
for (int i = 1; i <= n; ++i)a[i] = a[i - 1] + (s[i] == 'a');
for (int i = 1; i <= n; ++i)b[i] = b[i - 1] + (s[i] == 'b');
int ans = 0;
for (int i = 1; i <= n; ++i)
{
int l = i;
int r = n;
while (l < r)
{
int mid = (l + r + 1) >> 1;
check(i, mid) ? l = mid : r = mid - 1;
}
gmax(ans, l - i + 1);
}
printf("%d\n", ans);
}
return 0;
}
/*
【题意】
给你一个字符串,字符串中不是'a'就是'b'
我们可以修改最多k个位置。
问能够得到的最长相同字符的序列。
【类型】
前缀和二分答案or双指针
【分析】
直接维护前缀和(分别对'a'与'b'都求前缀和)
然后枚举左端点,可以对右端点二分或者利用双指针维护,就可以AC啦。
注意双指针做法要分别以维护a和维护b做两次双指针平移操作哦
【时间复杂度&&优化】
O(nlogn)->O(n)
*/