DESCRIPTION
给你一个01串,我们定义这个串的咸鱼值,是最长的全1串。现在你最多可以使用K次咸鱼魔法,每次魔法,你可以使得一个位置翻转(0变成1,1变成0)。问你这个串的咸鱼值最多是多少。
INPUT
第一行两个整数N,K。表示串的长度和可以施展咸鱼魔法的次数。(N,K<=300000)第二行N个01整数。
OUTPUT
输出答案。
SAMPLE INPUT
10 2
1 0 0 1 0 1 0 1 0 1
SAMPLE OUTPUT
5
题目分析:nexts记录每个1和0的后面的0的位置,要想得到最长的全1串,需要所有转换0的位置连在一起,所以可以遍历一遍数组,维护一个区间,区间内0的个数不超过k,这里nexts数组的作用是优化,在添加新元素0的个数超过k时可以方便的定位到区间的起点,答案为遍历过程中最长的区间。
//
// main.cpp
// 1124 - 咸鱼魔法记
//
// Created by teddywang on 2017/5/31.
// Copyright © 2017年 teddywang. All rights reserved.
//
#include <iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int n,k,s[400000],nexts[400000],t[400000];
int main()
{
while(~scanf("%d%d",&n,&k))
{
for(int i=0;i<n;i++)
scanf("%d",&s[i]);
memset(t,0,sizeof(t));
int num=0,numk=0,pos=0,ans=0;
for(int i=0;i<n;i++)
{
if(s[i]==0)
{
for(int j=pos;j<i;j++)
nexts[j]=i;//nexts 记录下一个0的位置,从0开始
pos=i;
}
}
nexts[pos]=pos;
pos=0;
for(int i=0;i<n;i++)
{
if(s[i]==1) num++;
else
{
numk++;
if(numk>k)
{
numk--;
if(s[pos]!=0) pos=nexts[pos];
pos++;
num=i-pos+1;
}
else num++;
}
ans=max(num,ans);
}
cout<<max(ans,num)<<endl;
}
}