Skip to content

Instantly share code, notes, and snippets.

@codecakes
Created September 27, 2022 13:10
Show Gist options
  • Save codecakes/abe710d4120341ed349336dd6a4d493b to your computer and use it in GitHub Desktop.
Save codecakes/abe710d4120341ed349336dd6a4d493b to your computer and use it in GitHub Desktop.
Max Consecutive Ones with 0 replacement
"""
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.
"""
class Solution:
def longestOnes(self, nums: List[int], k: int) -> int:
left = 0
zero_count = 0
max_ones = float("-inf")
for right, num in enumerate(nums):
if num == 0:
zero_count += 1
while (zero_count > k):
# print(f"zero_count={zero_count}")
if nums[left] == 0:
zero_count -= 1
left += 1
max_ones = max(max_ones, right - left + 1)
return max_ones
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment