Created
September 27, 2022 13:10
-
-
Save codecakes/abe710d4120341ed349336dd6a4d493b to your computer and use it in GitHub Desktop.
Max Consecutive Ones with 0 replacement
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
""" | |
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