DSA AnimatorDSA animations
Max Consecutive Ones III LC #1004 Medium Sliding Window
Problem

Given a binary array nums and an integer k, return the maximum number of consecutive 1s in the array if you can flip at most k 0s.

Example 1
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: Flip indices 3 and 4 → [1,1,1,1,1,1,1,1,1,1,0], window [0..5] = 6.
Example 2
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: Flip 3 zeros in the window [4..13] to get 10 consecutive 1s.
Constraints: 1 ≤ nums.length ≤ 10⁵ · nums[i] ∈ {0,1} · 0 ≤ k ≤ nums.length
Try Examples
Custom:
Approach
Sliding Window — At Most K Zeros
Expand right freely, counting zeros. When zeros exceed k, shrink from left until within budget. The window [L,R] always has ≤ k zeros (flipped to 1s). Track the max window size seen — O(n).
Sliding Window
Variables
L
—
R
—
zeros / k
—
maxLen
0
Step Logic
Press ▶ Play or Next Step to begin.
🎉
Ready
0 / 0
Select an example above and press Play.
Algorithm
1
L=0, zeros=0, maxLen=0 (sliding window init)
2
Expand R: if nums[R]==0, zeros++
3
Shrink L while zeros > k: if nums[L]==0, zeros--; L++
4
maxLen = max(maxLen, R−L+1); return maxLen
Time
O(n)
Space
O(1)
Why It Works

The window [L,R] always contains at most k zeros (which we can flip to 1s). When a new zero pushes us over budget, we slide L right until we're within budget again. The window size R−L+1 at each R gives the max window ending at R with at most k flips. We track the maximum over all R.

How to solve Max Consecutive Ones III

LeetCode 1004 · Medium · Arrays · Pattern: Sliding Window

Why the obvious approach is slow

Checking every subarray and counting its zeros is O(n²). Notice that a window is valid exactly when it contains at most k zeros.

The key idea

Grow a window to the right, and count the zeros inside it. When the zeros exceed k, shrink from the left until the window is valid again. The answer is the longest valid window seen.

Remember

At most k flips means a window with at most k zeros. Grow on the right, shrink on the left when the rule breaks.

Run the animation above on your own input, or watch the 1:42 video explanation of Max Consecutive Ones III with a dry run and Java code.

More Arrays problems