MediumArrayBinary SearchSliding WindowPrefix Sum

Max Consecutive Ones III

LeetCode
1 approach, code in all languages

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
You've got the patterns

Patterns get you through the screen. Shipping gets you hired.

FDE Coach is a cohort-based program in frontend, backend, AWS, and AI where you build real products and get referred to 200+ hiring partners. The free live workshop is the fastest way to see how we teach.

750+ engineers trained · frontend, backend, AWS & AI

August 15 · 0d left
Enroll Now