题目描述
给你一个01字符串,定义答案=该串中最长的连续1的长度,现在你有至多K次机会,每次机会可以将串中的某个0改成1,现在问最大的可能答案
输入描述:
输入第一行两个整数N,K,表示字符串长度和机会次数
第二行输入N个整数,表示该字符串的元素
( 1 <= N <= 300000
, 0 <= K <= N )
输出描述:
输出一行表示答案
输入例子1:
10 2
1 0 0 1 0 1 0 1 0 1
输出例子1:
5
Java代码
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int N = scanner.nextInt();
int K = scanner.nextInt();
int[] nums = new int[N];
for (int i = 0; i < N; i++) {
nums[i] = scanner.nextInt();
}
int left = 0;
int max = 0;
for (int i = 0; i < N; i++) {
if (nums[i] == 0) {
K--;
while (K < 0) {
if (nums[left] == 0) {
K++;
}
left++;
}
}
max=Math.max(i-left+1,max);
}
System.out.println(max);
}
}