Max Consecutive Ones III

medium

Find the longest subarray of 1s after flipping at most k zeros

Max Consecutive Ones III

Key Insight

Maintain window with at most k zeros. Shrink left when zero count exceeds k

Step 1Start Window
All onesZeros: 0, k: 2
L
R
1
0
1
1
1
2
0
3
0
4
0
5
1
6
1
7
1
8
1
9
0
10
[———]window

Begin expanding. First three elements are all ones.

1 / 5
Practice the Code

Step-by-Step Walkthrough: Max Consecutive Ones III

Maintain window with at most k zeros. Shrink left when zero count exceeds k

  1. Start Window

    Begin expanding. First three elements are all ones.

  2. Hit Zeros

    Window now contains two zeros, which equals our budget k.

  3. Too Many Zeros

    Third zero encountered. Zero count exceeds k, must shrink.

  4. Shrink Past Zeros

    Move left past zeros until count is back within budget.

  5. Maximum Window

    The longest window with at most 2 zeros has length 6.