Loading problems...
TL;DR: The optimal solution uses a variable-size sliding window to find the longest subarray containing at most k zeros.
The problem asks us to find the maximum length of a contiguous subarray of 1s, given that we are allowed to flip at most k 0s into 1s. This is a popular interview question that tests your ability to optimize subarray processing. In the context of LeetCode 1004, we are given a binary array nums and an integer k. We must return the length of the longest sequence of 1s possible after performing the allowed operations.
A naive approach to solving Max Consecutive Ones III involves iterating through every possible subarray, counting the number of zeros in each, and checking if that count is less than or equal to k. If the condition is met, we calculate the length of the subarray and update our maximum length.
max_len to 0.i from 0 to n-1 to represent the start of the subarray.j from i to n-1 to represent the end of the subarray.i to j to count zeros.≤ k, update max_len = max(max_len, j - i + 1).textfunction bruteForce(nums, k): max_len = 0 n = length of nums for i from 0 to n-1: for j from i to n-1: zero_count = 0 for p from i to j: if nums[p] == 0: zero_count += 1 if zero_count <= k: max_len = max(max_len, j - i + 1) return max_len
The time complexity of this approach is O(N³) because of the three nested loops (or O(N²) if the zero count is maintained incrementally in the inner loop). Given the constraint nums.length <= 10^5, an O(N²) solution performs approximately 10^{10} operations, which far exceeds the typical limit of 10^8 operations per second allowed by online judges. This will result in a Time Limit Exceeded (TLE) error.
The key intuition for LeetCode 1004 is to reframe the problem statement. Instead of thinking about "flipping" zeros, we should view the problem as finding the longest subarray with at most k zeros. If a subarray has k or fewer zeros, we can theoretically flip all of them to 1s to form a consecutive sequence of 1s.
The sliding window technique allows us to maintain a valid window [left, right] where the count of zeros is always less than or equal to k.
right pointer) to try and find a longer valid subarray.k, the window becomes invalid. To restore validity, we shrink the window from the left (left pointer) until the zero count drops back to k.[left, right] contains at most k zeros.Visual Description: Imagine a window expanding over the array. The right edge moves forward, consuming elements. When a zero is consumed, an internal counter increments. If this counter exceeds k, the left edge of the window moves forward, dropping elements. If a zero is dropped, the counter decrements. This "caterpillar-like" movement ensures we efficiently check all valid windows without redundant recalculations.

Let's trace the algorithm with nums = [1,1,1,0,0,0,1,1,1,1,0] and k = 2.
left = 0, right = 0, zeros = 0, max_len = 0.nums[right] is 1. zeros remains 0. max_len updates to 3.nums[3] is 0. zeros becomes 1. 1 <= 2, valid. max_len updates to 4.nums[4] is 0. zeros becomes 2. 2 <= 2, valid. max_len updates to 5.nums[5] is 0. zeros becomes 3. Constraint violated (3 > 2).
nums[left] (index 0) is 1. left moves to 1. zeros is still 3.nums[left] (index 1) is 1. left moves to 2. zeros is still 3.nums[left] (index 2) is 1. left moves to 3. zeros is still 3.nums[left] (index 3) is 0. zeros becomes 2. left moves to 4.[4, 5] (values 0, 0). Valid. max_len remains 5.right moves through 1s. Window expands. zeros remains 2. max_len updates eventually to 6 (window [5, 10]).The algorithm correctly identifies the longest valid window length as 6.
The correctness relies on the invariant that for any right index, the algorithm finds the smallest left index such that the subarray nums[left...right] contains at most k zeros.
while loop ensures that we never consider an invalid window for the maximum length calculation. If zeros > k, we shrink until valid.right iterates from 0 to n-1 and left only moves forward when necessary, we consider the largest possible valid window ending at every index right. The global maximum of these local maximums must be the overall maximum length.cppclass Solution { public: int longestOnes(vector<int>& nums, int k) { int left = 0; int right = 0; int zeros = 0; int max_len = 0; while (right < nums.size()) { // Expand the window if (nums[right] == 0) { zeros++; } // Shrink the window if constraint is violated while (zeros > k) { if (nums[left] == 0) { zeros--; } left++; } // Update maximum length found so far max_len = max(max_len, right - left + 1); right++; } return max_len; } };
javaclass Solution { public int longestOnes(int[] nums, int k) { int left = 0; int right = 0; int zeros = 0; int maxLen = 0; while (right < nums.length) { // Add new element to the window if (nums[right] == 0) { zeros++; } // Contract window if invalid while (zeros > k) { if (nums[left] == 0) { zeros--; } left++; } // Update global maximum maxLen = Math.max(maxLen, right - left + 1); right++; } return maxLen; } }
pythonclass Solution: def longestOnes(self, nums: List[int], k: int) -> int: left = 0 zeros = 0 max_len = 0 for right in range(len(nums)): # Expand window logic if nums[right] == 0: zeros += 1 # Shrink window logic while zeros > k: if nums[left] == 0: zeros -= 1 left += 1 # Update max length max_len = max(max_len, right - left + 1) return max_len
Time Complexity: O(N)
The right pointer iterates through the array once. The left pointer also iterates through the array at most once (it never moves backward). Therefore, the total number of operations is proportional to 2 * N, which simplifies to linear time O(N).
Space Complexity: O(1)
We only use a few integer variables (left, right, zeros, max_len) for state tracking. No auxiliary data structures proportional to the input size are used.
The Sliding Window - Variable Size pattern is highly reusable. Understanding the logic for LeetCode 1004 helps in solving:
>= target.k.In all these cases, the core logic remains: expand right to satisfy a requirement, then shrink left to optimize or restore validity.
Q: Why does the naive solution get Time Limit Exceeded (TLE)? Mistake: Using nested loops to check every subarray. Why: This results in O(N²) complexity. With N=100,000, the algorithm performs 10 billion operations, exceeding the typical 1-second time limit. Consequence: The solution is correct but too slow to pass all test cases.
Q: Why is my output smaller than the expected answer?
Mistake: Resetting the window entirely (setting left = right) when zeros > k.
Why: This discards valid parts of the window. You only need to shrink from the left until the zero count is valid again.
Consequence: You miss valid windows that overlap with the previous window, leading to an incorrect (suboptimal) answer.
Q: Why do I get an Index Out of Bounds error?
Mistake: Incrementing pointers without checking array bounds, or incorrect while loop conditions.
Why: Usually happens if the shrinking logic (left++) runs without ensuring left <= right or left < n.
: Runtime error causing the program to crash.
Q: Can I use recursion for this problem? Mistake: Attempting a recursive DFS to simulate flipping bits. Why: This treats the problem as a decision tree (flip or don't flip), which is O(2^N). Consequence: Immediate TLE and stack overflow for large inputs.