MediumArrayBinary SearchSliding WindowPrefix Sum

1 approach, code in every language

Problem description

You are given a binary array nums containing only 0s and 1s, together with an integer k. You may flip at most k of the zeros into ones.

Return the length of the longest contiguous run of ones you can obtain after performing those flips optimally.

Equivalently, find the longest subarray that contains no more than k zeros, since those zeros are exactly the ones you would flip.

Example 1

Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2

Output: 6

Flipping two of the zeros in the middle yields the run [1,1,1,0,0,1,1,1,1] trimmed to a window of six consecutive ones.

Example 2

Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3

Output: 10

A window covering ten positions can be made all ones by flipping at most three zeros inside it.

Constraints

  • 1 <= nums.length <= 10^5
  • nums[i] is either 0 or 1.
  • 0 <= k <= nums.length

After the pattern

Now solve one you haven't seen.

Longest Verified Backup Streak is our own problem on the technique behind Max Consecutive Ones III: a new statement, so there's no answer to remember. Write it in your browser and run it against graded tests.

1,194 problems · 15,062 graded tests · free