#354(Div.2)C.Vasya and String

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?

Input
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.

Output
Print the only integer — the maximum beauty of the string Vasya can achieve by changing no more than k characters.

Examples
Input

4 2
abba

Output

4

Input

8 1
aabaabaa

Output

5

这个题的意思是是给你一个长度为n并且只含ab的字符串,并且有k次修改机会,使得修改完后的字符串得到一个有最长的含有连续相同字母的子串长度。

题目分析:
首先,用a[]、b[]数组分别存储第i位到第一位中a的数量和b的数量。
然后枚举所有点,将其做为起点,然后往后用二分寻找终点,用ans存储找到最大的长度即可。

上代码:

#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
#include <algorithm>
#include <iomanip>
#define LL long long
const int N=1e5+5;
using namespace std;
int  a[N],b[N];
char s[N]; 
int main()
{
 cin.tie(0);                  //解除cin和cout的绑定加快cin的速度
 ios::sync_with_stdio(false); //再次加快cin的速度,但不能再用scanf了
 int n,k;
 cin>>n>>k;
 cin>>s+1;
 for(int i=1;i<=n;i++)
 {                            //a存储s的1-i中a的个数,b存储s的1-i中b的个数               
  if(s[i]=='a') a[i]=a[i-1]+1,b[i]=b[i-1];
  else a[i]=a[i-1],b[i]=b[i-1]+1;
 }
 int ans=0;
 for(int i=1;i<=n;i++)
 {
  int l=i,r=n,mid;
  while(r>=l)                //二分查找终点
  {
   mid=l+r>>1;
   if(a[mid]-a[i-1]<=k||b[mid]-b[i-1]<=k)
   {                         //如果a或b的的数量小于等于k(即修改小于k次)
       ans=max(ans,mid-i+1);//则满足条件用其长度与ans比较,求最大值
       l=mid+1; 
   }
   else r=mid-1;
   }
 }
 cout<<ans<<endl;     //输出答案
 return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lwz_159

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值