Max Consecutive Ones III (LeetCode 1004): Solution and Explanation
Given a binary array and a budget of k flips from 0 to 1, return the length of the longest run of ones you can make.
Intuition
You never need to decide which zeros to flip up front. Any stretch of the array that contains at most k zeros can be turned into all ones, so the question becomes: what is the longest subarray with at most k zeros?
Checking every subarray costs O(n^2). But if a window with too many zeros is invalid, any wider window around it is invalid too, so the left edge never needs to move back.
Grow the window one element at a time on the right. Each zero that enters spends one flip. When the window holds more than k zeros, move the left edge forward until a zero leaves and its flip comes back.
After that, the window is valid again and its length is a candidate for the answer. Both edges only move forward, so the whole scan is linear.
Approach: Sliding window with a zero counter
- Set
left = 0,zeros = 0andbest = 0. - For each
right, ifnums[right]is 0, add one tozeros. - While
zeros > k, checknums[left]: if it is 0, subtract one fromzeros. Then moveleftone step right. - The window
[left, right]now holds at most k zeros. Setbest = max(best, right - left + 1). - Return
best.
Step-by-step example
nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
- Indices 0 to 4 enter. The zeros at 3 and 4 use both flips, and the window
[0, 4]has length 5, sobest = 5. - Index 5 is a third zero.
zeros = 3 > 2, soleftmoves past the ones at 0, 1 and 2 and then past the zero at 3, ending atleft = 4withzeros = 2. - Indices 6 to 9 are ones. The window grows to
[4, 9], length 6, sobest = 6. - Index 10 is a zero.
leftmoves past the zero at 4, giving[5, 10], length 6. The answer stays 6.
Code: Python, Java, C++
1class Solution:
2 def longestOnes(self, nums: List[int], k: int) -> int:
3 left = 0
4 zeros = 0
5 best = 0
6 for right in range(len(nums)):
7 if nums[right] == 0:
8 zeros += 1
9 while zeros > k:
10 if nums[left] == 0:
11 zeros -= 1
12 left += 1
13 best = max(best, right - left + 1)
14 return best1class Solution {
2 public int longestOnes(int[] nums, int k) {
3 int left = 0, zeros = 0, best = 0;
4 for (int right = 0; right < nums.length; right++) {
5 if (nums[right] == 0) zeros++;
6 while (zeros > k) {
7 if (nums[left] == 0) zeros--;
8 left++;
9 }
10 best = Math.max(best, right - left + 1);
11 }
12 return best;
13 }
14}1class Solution {
2public:
3 int longestOnes(vector<int>& nums, int k) {
4 int left = 0, zeros = 0, best = 0;
5 for (int right = 0; right < (int)nums.size(); right++) {
6 if (nums[right] == 0) zeros++;
7 while (zeros > k) {
8 if (nums[left] == 0) zeros--;
9 left++;
10 }
11 best = max(best, right - left + 1);
12 }
13 return best;
14 }
15};Time and space complexity
O(n)
right visits each index once and left moves forward at most n times across the whole scan.
O(1)
Only the two edges, the zero count and the best length are stored.
Other approaches
Non-shrinking window (time O(n), space O(1))
Replace the while with an if: when the window holds too many zeros, slide it by one instead of shrinking it. The window size never drops, so at the end right - left + 1 is the answer.
Prefix zero counts with binary search (time O(n log n), space O(n))
Build prefix counts of zeros, then for each right edge binary search the smallest left edge whose window holds at most k zeros.
Try every window (time O(n^2), space O(1))
For each start, extend right while the zero count stays within k. Easy to write but quadratic.
Common mistakes
- Decrementing
zerosfor every element that leaves, instead of only for zeros. - Moving
leftbefore checkingnums[left], which checks the wrong element. - Recording
bestbefore the shrinking loop finishes, when the window still holds too many zeros. - Forgetting the k = 0 case: the window must then contain only ones, and an all-zero array gives 0.
Frequently asked questions
Do I need to remember which zeros were flipped?
No. Every zero inside the window counts as flipped, so a single counter is enough.
How is this related to Max Consecutive Ones?
Max Consecutive Ones is the k = 0 case. This version adds a budget, which turns a simple run counter into a sliding window.
Why is the inner while loop still O(n) overall?
Each pass moves left forward by one, and left never goes back, so it moves at most n times in total.