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: 4Explanation:
Example 2:
Input: nums = [1,0,1,1,0,1]
Output: 4Explanation:
Constraints:
1 <= nums.length <= 10^5nums[i] is either 0 or 1.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?
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
longest_sequence = 0
for left in range(len(nums)):
num_zeroes = 0
for right in range(left, len(nums)): # Check every consecutive sequence
if num_zeroes == 2:
break
if nums[right] == 0: # Count how many 0's
num_zeroes += 1
if num_zeroes <= 1: # Update answer if it's valid
longest_sequence = max(longest_sequence, right - left + 1)
return longest_sequenceWhere is the length of the input array
nums.
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
longest_sequence = 0
left, right = 0, 0
num_zeroes = 0
while right < len(nums): # While our window is in bounds
if nums[right] == 0: # Increase num_zeroes if the rightmost element is 0
num_zeroes += 1
while num_zeroes == 2: # If our window is invalid, contract our window
if nums[left] == 0:
num_zeroes -= 1
left += 1
longest_sequence = max(longest_sequence, right - left + 1) # Update our longest sequence answer
right += 1 # Expand our window
return longest_sequenceWhere is the length of the input array
nums.