Max Consecutive Ones III

MediumSliding Windowsliding window

Solve this the way you would in the interview: out loud, on a timer, with an AI interviewer asking follow-ups while you code. You get a scored report at the end.

Practice this as a mock interviewFree to start, no account needed

Problem

You are given a binary array nums (every element is either 0 or 1) and an integer k. You are allowed to flip at most k zeros into ones. After performing these flips, return the length of the **longest contiguous run** of 1s that can be obtained. In other words, find the maximum length of a subarray that contains **at most k zeros** — those zeros can all be flipped to 1, producing an unbroken block of ones of that length. If no flips are needed (or k is large enough to cover every zero in a window), the answer is simply the length of the best such window.

Examples

Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Flipping the two zeros at indices 3 and 4 gives [1,1,1,1,1,1,1,1,1,1,0] over the window from index 0 to 5, a run of 6 ones. Flipping the last two zeros of the trailing group also yields 6.
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
Flipping the zeros at indices 4, 5, and 9 turns the window from index 3 to 12 into ten consecutive ones.
Input: nums = [1,0,1,0,1,0,1], k = 0
Output: 1
With no flips allowed, the longest run of ones already present has length 1.

Constraints

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

What the interviewer grades

A correct solution is one of five scores. The report also grades problem understanding (did you clarify inputs and edge cases before coding), problem solving, communication while you work, code quality, and testing. See a sample report, or read up on the pattern in the lessons.

More sliding window problems