Max Consecutive Ones III
Master this topic with zero to advance depth.
Max Consecutive Ones III
Given a binary array nums and an integer k, return the maximum number of consecutive 1's in the array if you can flip at most k 0's.
Visual Representation
nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
L R
| |
1 1 1 0 0 0 1 1 1 1 0
[-----] (Zeros: 1 <= 2, Expand R)
L R
| |
1 1 1 0 0 0 1 1 1 1 0
[-------] (Zeros: 2 <= 2, Expand R)
L R
| |
1 1 1 0 0 0 1 1 1 1 0
[---------] (Zeros: 3 > 2! Shrink L)Examples
Level I: Brute Force
Intuition
Check every possible subarray and count the number of zeros in it. If the zero count is less than or equal to k, the subarray is valid. Keep track of the maximum length of such valid subarrays.
Thought Process
- Use two nested loops to define all possible subarrays
[i, j]. - In the inner loop, count zeros.
- If
zeros <= k, updatemaxLen = max(maxLen, j - i + 1). - If
zeros > k, break the inner loop (optimization).
Detailed Dry Run
| i | j | nums[j] | Zeros | Max Len | Action |
|---|---|---|---|---|---|
| 0 | 0 | 1 | 0 | 1 | Update |
| 0 | 3 | 0 | 1 | 4 | Update |
| 0 | 4 | 0 | 2 | 5 | Update |
| 0 | 5 | 0 | 3 | 5 | Break (Zeros > k) |
Level II: Binary Search on Answer (O(N log N))
Intuition
We can binary search for the maximum possible length L of a valid subarray. For a fixed length L, we can check if there exists any subarray of length L with at most k zeros using a fixed-size sliding window in time.
Thought Process
- Search range for length is
[0, n]. - For a fixed
midlength:- Slide a window of size
midacross the array. - Count zeros in the window.
- If any window has
zeros <= k, thenmidis possible.
- Slide a window of size
- If possible, search higher; else search lower.
Pattern: Search on Answer Space
Level III: Optimal (Sliding Window)
Intuition
Thought Process
Instead of checking every subarray, we use a window [left, right]. We expand the window by moving right. If the number of zeros in the window exceeds k, we must shrink the window from the left until the zero count is back to k.
Pattern: Variable Size Sliding Window
- Expand:
windowSum += (nums[right] == 0 ? 1 : 0) - Constraint:
zeros > k - Shrink:
while (zeros > k) { if (nums[left] == 0) zeros--; left++; }
Detailed Dry Run
| R | Num | Zeros | Action | Max Len |
|---|---|---|---|---|
| 3 | 0 | 1 | Expand | 4 |
| 4 | 0 | 2 | Expand | 5 |
| 5 | 0 | 3 | Shrink L (until zeros=2) | 5 |
| 10 | 0 | 2 | Expand | 6 |
⚠️ Common Pitfalls & Tips
Be careful with the while loop condition. It should be zeros > k. Also, ensure you update maxLen after the shrink loop is done to ensure the window is valid.
Found an issue or have a suggestion?
Help us improve! Report bugs or suggest new features on our Telegram group.