Max Consecutive Ones III

Med
Concept
Code
Loading editor...
Tap Analyze to see visualization
Variables

Run code to see variables

Output

Console output will appear here

Press Space to start to step? all shortcuts

Solution Guide: Max Consecutive Ones III

Approach

Maintain a window where the number of zeros does not exceed k. Expand right and count zeros. When zero count exceeds k, shrink from the left until the count is valid again. The window length at each step represents a valid sequence of 1s with at most k flips.

Complexity Analysis

Time
O(n)
Space
O(1)

Pattern

Sliding Window (Variable Size)

Why It Works

The window invariant guarantees at most k zeros inside, meaning all zeros in the window can be flipped to 1s. By tracking zero count instead of actually flipping, we efficiently find the longest valid subarray in a single pass.

Updated Feb 2026