Max Consecutive Ones III
On this page
Problem statement
Given a binary array and an integer k, return the length of the longest run of consecutive 1s you can get by flipping at most k zeros to 1.
Reworded, it asks for the longest subarray that contains at most k zeros. That makes it a textbook variable-size sliding window, the same shape as "longest substring with at most k distinct characters" or "longest streak with at most k missed days". Original problem: LeetCode 1004.
Example

Input: nums = [1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 1], k = 2
Output: 7 # indices 2..8
Input: same nums, k = 0
Output: 3 # no flips: the longest existing run, indices 6..8
Constraints (assumed)
- 1 ≤ n ≤ 10⁵; every element is 0 or 1; 0 ≤ k ≤ n.
What this question tests
- Rephrasing "flip at most k" as "a window with at most k zeros".
- Writing a sliding window with a clean shrink condition.
- Explaining why it's O(n) even with a nested
while.
Questions to ask first
- Must I flip exactly k zeros, or at most k? (Here: at most.)
- Can k be 0, or larger than the number of zeros? (Here: both; the code handles them without special cases.)
- Do you need the length or the positions? (Here: the length.)
- Is the data a stream? The window approach works on a stream; prefix-sum approaches don't as easily.
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.