Leetcode # 487. Max Consecutive Ones II

Problem

https://leetcode.com/problems/max-consecutive-ones-ii

相關例題

Solution

Time Complexity: O(len(nums))
Space Complexity: O(1)
(The input and output generally do not count towards the space complexity.)

class Solution:
  def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
    ans = left  = flipped = 0
    for right in range(len(nums)):
      # do logic here to add arr[right] to curr
      if nums[right] == 0: flipped += 1

      while left <= right and flipped > 1:
        # remove arr[left] from curr
        if nums[left] == 0: flipped -= 1
        left += 1

      # update ans
      ans = max(ans, right - left + 1)
    
    return ans

Last Updated on 2023/08/29 by A1go

目錄
Bitnami