InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Sliding Window

Max Consecutive Ones III

medium Original ↗ 00:00

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 = 26 — 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 = 310 — flip the zeros at indices 4, 5, and 9 to connect indices 2–11.
  • nums = [0, 0, 0], k = 00 — 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug