← Back to DSA Animator
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.