Max Consecutive Ones III Solution
Given a binary array nums and an integer k, return the maximum number of consecutive 1s you can obtain if you may flip at most k zeroes.
Problem Statement
This is a classic longest valid window problem. A window is valid if it contains at most k zeroes, because those are exactly the positions we can flip to ones. So the job becomes: find the longest subarray with at most k zeroes.
Brute Force β Expand from Every Start
For each starting index, extend the subarray rightward and count how many zeroes appear. As long as the zero count stays within k, the window is valid and can update the answer. Once zeroes exceed k, we can stop extending from that start.
| Metric | Value |
|---|---|
| Time | O(nΒ²) |
| Space | O(1) |
Sliding Window β Longest Valid Window
Maintain a window [left, right] and count how many zeroes it currently contains. Expand right every step. If the zero count becomes greater than k, shrink from the left until the window is valid again. The answer is the maximum valid window length seen.
k broken bulbs inside a display case. As you extend the case to the right, each new bulb enters. If too many broken bulbs accumulate, you slide the left edge forward until the case is affordable again. The widest affordable case is the answer.
- Step 1: Initialize
left = 0,zeroes = 0, andbest = 0. - Step 2: For each
right, ifnums[right] == 0, incrementzeroes. - Step 3: While
zeroes > k, shrink from the left. Ifnums[left] == 0, decrementzeroes. - Step 4: After the window is valid again, update
best = max(best, right - left + 1).
- Problems of the form βlongest subarray with at most K bad elementsβ almost always use this exact template.
- The only thing that changes is what counts as βbadβ β here it is a zero.
Visual Walkthrough
Trace through nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2:
Code β Java & Python
Complexity Analysis
| Approach | Time | Space | Trade-off |
|---|---|---|---|
| Expand from each start | O(nΒ²) | O(1) | Simple but repeats zero-count work |
| Sliding window β optimal | O(n) | O(1) | Each index enters and leaves the window once |
Edge Cases & Pitfalls
| Case | Input | Why It Matters |
|---|---|---|
| k = 0 | [1,1,0,1], k=0 | No flips allowed β answer is longest natural run of ones. |
| Enough flips for all zeroes | [0,1,0,1], k=2 | Whole array becomes valid. |
| All ones | [1,1,1], k=1 | Answer is array length. |
| All zeroes | [0,0,0], k=2 | Best answer is limited by how many zeroes we can flip. |
| Single element | [0], k=1 | Smallest non-trivial case. |
nums at all. Just count how many zeroes are inside the current window and enforce zeroes β€ k.