Problem
Given a binary arraynums and an integer k, return the maximum number of consecutive 1’s in the array if you can flip at most k 0’s.
Examples
Constraints
1 <= nums.length <= 10^5nums[i]is either0or1.0 <= k <= nums.length
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 1004 with 12 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 1004 # by problem number
lcpy gen -s max_consecutive_ones_iii # by problem name
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.
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.
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.
1 <= nums.length <= 10^5nums[i] is either 0 or 1.0 <= k <= nums.lengthclass Solution:
# Time: O(n)
# Space: O(1)
def longest_ones(self, nums: list[int], k: int) -> int:
left = 0
zeros = 0
best = 0
for right, num in enumerate(nums):
if num == 0:
zeros += 1
while zeros > k:
if nums[left] == 0:
zeros -= 1
left += 1
best = max(best, right - left + 1)
return best
| Time | Space |
|---|---|
| O(n) | O(1) |