InterviewPrepKit

Home / Coding / Sliding Window

Max Consecutive Ones III

medium Original β†—
Solving tips
  • Restate 'flip at most k zeros' as 'longest window containing at most k zeros', the classic operation-budget-to-window translation.
  • Maintain a running zero count; grow right unconditionally and shrink left while zeros > k, tracking the max window size.
  • Validity (at most k zeros) is monotone under shrinking, so both pointers move forward only, giving O(n) time and O(1) space.
  • Common pitfall: record best only after restoring validity, and decrement the zero count only when the element leaving left is actually a 0.

Problem

You are given a binary array nums (each element is 0 or 1) and an integer k. You may flip at most k zeros into ones. Return the length of the longest run of consecutive 1s achievable after the flips.

Reworded without flipping: find the longest contiguous subarray that contains at most k zeros β€” flipping exactly those zeros makes it all ones.

Examples

  • nums = [1, 1, 1, 0, 0, 0, 1, 1, 1, 1, 0], k = 2 β†’ 6 β€” flip the zeros at indices 5 and 10, making indices 5–10 six consecutive 1s (flipping indices 4 and 5 instead also yields a run of 6).
  • nums = [0, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], k = 3 β†’ 10 β€” flip the zeros at indices 4, 5, and 9 to connect indices 2–11.
  • nums = [0, 0, 0], k = 0 β†’ 0 β€” no flips allowed and no 1s present.

Constraints

  • 1 <= len(nums) <= 10^5
  • nums[i] is 0 or 1
  • 0 <= k <= len(nums)

Enumerating all O(nΒ²) subarrays and counting their zeros is ~10^10 steps at the top end; the expected solution is one O(n) pass.

Think about it first

Hint 1 Forget flipping β€” restate the goal: longest window containing at most k zeros. Which single number summarizes a window for this test?
Hint 2 If a window has at most k zeros, so does any window inside it; if it has more, so does any window around it. Monotone validity means two forward-only pointers suffice.
Hint 3 Keep a running count of zeros in the window. Advance right each step (count the entering zero); while the count exceeds k, advance left (uncount the leaving zero). Track the largest window ever valid.
Your workspace Not runnable by design β€” this is your interview scratchpad. Saved on this device.