13 · Sliding Window

#1004 Max Consecutive Ones III

Mediumsolve on LeetCode ↗

frequently reported atLinkedInMetaAmazonMicrosoftGoogle

the problem

In plain words

nums holds only 0s and 1s. You may turn up to k of the 0s into 1s. How long can the longest unbroken run of 1s become?

in nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2

out 6

Flip the 0s at indices 5 and 10: nums[5..10] becomes six 1s in a row.

in nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3

out 10

  • 1 ≤ n ≤ 10⁵
  • nums[i] is 0 or 1
  • 0 ≤ k ≤ n

your turn

Try it before you peek

Read the examples, say the brute force out loud, then write code: here or on LeetCode ↗. Stuck for 20 minutes? Open one hint at a time.

Solve it in the browser

LeetCode-style: complete the class. Compiled by the real javac (Java 17) and judged right here — nothing is sent anywhere.

    Solutions are hidden so you can try first. Even 20 minutes of real effort makes the answer stick far better than reading it.

    Marking the problem solved, or opening every hint, also shows it.

    practise next

    Similar problems

    1. #424
    2. #3
    3. #209
      Minimum Size Subarray Sum
      Mediumin Sliding Window