Max Consecutive Ones III

Free with account Updated Nov 19, 2026 · 4 min read
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

    Flipping the zeros at indices 4 and 5 (yellow) joins two runs into seven consecutive 1s.
    Flipping the zeros at indices 4 and 5 (yellow) joins two runs into seven consecutive 1s.
    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

    1. Must I flip exactly k zeros, or at most k? (Here: at most.)
    2. Can k be 0, or larger than the number of zeros? (Here: both; the code handles them without special cases.)
    3. Do you need the length or the positions? (Here: the length.)
    4. Is the data a stream? The window approach works on a stream; prefix-sum approaches don't as easily.