Skills101
← All coding problems

Max Consecutive Ones III

mediumSliding Window+20 XPTime limit 2s

The array contains only 0s and 1s. You may flip at most k zeros into ones. What is the longest run of consecutive 1s you can get?

Input:

  • line 1: n k
  • line 2: n values (each 0 or 1)

Output: the maximum length.

Constraints: 1 ≤ n ≤ 10⁵, 0 ≤ k ≤ n.

Think about it: rephrase it — find the longest window that contains at most k zeros.

Sample input 1

11 2
1 1 1 0 0 0 1 1 1 1 0

Sample output 1

6

Sample input 2

19 3
0 0 1 1 0 0 1 1 1 0 1 1 0 0 0 1 1 1 1

Sample output 2

10

📖 Stuck? Learn the pattern

Read input from standard input and print the answer to standard output. Your code runs in a secure sandbox against the samples (Run) and hidden tests (Submit).

Loading editor…

Log in to run and submit your code — it's free.