Max Consecutive Ones II Problem
Description
LeetCode Problem 487.
Given a binary array nums, return the maximum number of consecutive 1's in the array if you can flip at most one 0.
Example 1:
Input: nums = [1,0,1,1,0]
Output: 4
Explanation:
- If we flip the first zero, nums becomes [1,1,1,1,0] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1] and we have 3 consecutive ones.
The max number of consecutive ones is 4.
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 4
Explanation:
- If we flip the first zero, nums becomes [1,1,1,1,0,1] and we have 4 consecutive ones.
- If we flip the second zero, nums becomes [1,0,1,1,1,1] and we have 4 consecutive ones.
The max number of consecutive ones is 4.
Constraints:
1 <= nums.length <= 10^5nums[i]is either0or1.
Follow up: What if the input numbers come in one by one as an infinite stream? In other words, you can't store all numbers coming from the stream as it's too large to hold in memory. Could you solve it efficiently?
Solution
Approach: Sliding Window
Flipping at most one 0 means we are looking for the longest subarray that contains at most one zero. A sliding window finds it in one pass.
Move the right end over the array and count the zeros inside the window (x ^ 1 is 1 exactly when x is 0). As long as the window has at most one zero, it is a valid answer. When a second zero comes in, the window becomes invalid, and we move the left end one step to the right, taking the zero count of the element that leaves with it.
Notice that the left end moves only one step, not until the window is valid again. We only care about the largest valid length, so the window never needs to shrink: an invalid window simply slides along at the best length seen so far, and it grows again only when a longer valid window appears. That is why the answer at the end is just the window's length, n - left.
For example, in [1,0,1,1,0] the window grows to [1,0,1,1] (length 4); the second zero makes it slide to [0,1,1,0], still length 4, so the answer is 4.
This also answers the follow-up: if the numbers come from a stream, store only the position of the last zero instead of the array. When a new zero arrives, the window restarts right after the previous zero.
Complexity: O(n) time and O(1) extra space.
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
left = zeros = 0
for x in nums:
zeros += x ^ 1
if zeros > 1:
# slide the window: it keeps its best length and never shrinks
zeros -= nums[left] ^ 1
left += 1
return len(nums) - left