Max Consecutive Ones III Problem
Description
LeetCode Problem 1004.
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.
Example 1:
Input: nums = [1,1,1,0,0,0,1,1,1,1,0], k = 2
Output: 6
Explanation: [1,1,1,0,0,1,1,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Example 2:
Input: nums = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], k = 3
Output: 10
Explanation: [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
Bolded numbers were flipped from 0 to 1. The longest subarray is underlined.
Constraints:
1 <= nums.length <= 10^5nums[i]is either 0 or 1.0 <= k <= nums.length
Solution
Approach: Sliding Window
Flipping at most k zeros and asking for the longest run of 1s is the same as asking for the longest subarray that contains at most k zeros: we can flip every zero inside it.
Move a right end i across the array and keep a left end left, counting the zeros in nums[left..i]. When the count goes above k, the window is invalid, and the usual fix is to move left forward until it is valid again.
We can be lazier. We only want the largest valid window, so the window never needs to shrink: when it becomes invalid, move left forward by exactly one step, so the window slides right without changing size. It may stay invalid for a while, but its size is always the size of the best valid window seen so far, and it only grows when the window ending at i is valid. So at the end the answer is simply the window's size, n - left.
In Example 1 the window grows to size 6 at nums[4..9] = [0,0,1,1,1,1] (two zeros), then slides one step to the right when the last 0 comes in.
Complexity: O(n) time and O(1) extra space.
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
left = zeros = 0 # the window is nums[left..i]; zeros = number of 0s in it
for x in nums:
zeros += x ^ 1
if zeros > k:
# Too many 0s: slide the whole window right by one, so it never shrinks.
zeros -= nums[left] ^ 1
left += 1
return len(nums) - left