smj007

Untitled

Mar 15th, 2025
597
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.84 KB | None | 0 0
  1. class Solution:
  2.     def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
  3.  
  4.         # take a sliding window approach
  5.         # sliding window approaches are based on expansion and contractions
  6.         # when you find an ideal state - you expand
  7.         # when you find a valid stte - you contract
  8.         # ideal condition is decided by the number of zeros in the sliding window
  9.  
  10.         left = 0
  11.         right = 0
  12.         countZeroes = 0
  13.         maxConsecutiveOnes = -1
  14.  
  15.         while (right < len(nums)):
  16.             if nums[right]==0:
  17.                 countZeroes += 1
  18.  
  19.             if countZeroes >= 2:
  20.                 if nums[left]==0:
  21.                     countZeroes -= 1
  22.                 left += 1
  23.  
  24.             maxConsecutiveOnes = max(maxConsecutiveOnes, right-left+1)
  25.             right += 1
  26.  
  27.         return maxConsecutiveOnes
Advertisement
Add Comment
Please, Sign In to add comment