mediumSliding WindowTwo PointersSliding Window

Max Consecutive Ones III

mediumTime: O(n)Space: O(1)

Recognize the pattern

longest subarray of 1s after flipping at most k zeroscontiguous window with limited flips

Brute force idea

A straightforward first read of Max Consecutive Ones III is this: Try every subarray, count zeros, check if ≤ k. Each subarray independently counts its zeros. That instinct is useful because it follows the prompt literally, but it usually keeps revisiting work the problem is begging you to organize.

Better approach

A calmer way to see Max Consecutive Ones III is this: Sliding window: expand right; when zero count exceeds k, shrink left. The window always contains at most k zeros. Track the maximum window length. The goal is not to be clever for its own sake, but to remember the one relationship that keeps the solution grounded as you move forward.

Key invariant

The truth you want to protect throughout Max Consecutive Ones III is this: The window represents a subarray where at most k zeros have been 'flipped' to ones. All elements in the window are either 1 or a flipped 0. If that remains true after every update, the rest of the reasoning has a stable place to stand.

Watch out for

One easy way to drift off course in Max Consecutive Ones III is this: Actually flipping the zeros in the array — don't modify the array. Just count zeros in the window and pretend they're flipped. The fix is usually to return to the meaning of each move, not just the steps themselves.

Sliding Window Pattern