487. Max Consecutive Ones II

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: 4 Explanation: Flip the first zero will get the maximum number of consecutive 1s. After flipping, the maximum number of consecutive 1s is 4.
Example 2: Input: nums = [1,0,1,1,0,1] Output: 4

  • code
class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        l = r = 0
        res = 0
        count0 = 0

        while r < len(nums):
            if nums[r] == 0:
                count0 += 1
                
            while count0 == 2:
                if nums[l] == 0:
                    count0 -= 1
                l += 1
                
            res = max(res, r - l + 1)
            r += 1
            
        return res
  • code
class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        count_last = count = res = 0
        if len(nums) == 1: return 1
        
        for i in range(len(nums)):
            if nums[i] == 1:
                count += 1
            else:
                if i >= count + 2 and nums[i-count-2] == 1:
                    res = max(count_last + count + 1, res)
                count_last = count
                count = 0
        if i >= count + 1 and nums[i-count-1] == 1:
            res = max(count_last + count + 1, res)
        if count == 0:
            return max(res, count_last + 1)
        return min(max(res, count + 1), len(nums))