Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nasifimtiazohi/96b67890c2cb920b806222c13d63ef08 to your computer and use it in GitHub Desktop.
Save nasifimtiazohi/96b67890c2cb920b806222c13d63ef08 to your computer and use it in GitHub Desktop.
class Solution:
def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
def NextStripLen(nums, i):
if not i< len(nums):
return 0
j=i+1
c=1
while j<len(nums) and nums[j]==nums[i]:
c+=1
j+=1
return c
#edge case
if not nums:
return 0
i=0 #i starts from first one strip
#if first element zero, count it, and move to the first one strip
if nums[i]==0:
l=NextStripLen(nums,i)
i+=l
longest=1 #minimum one. Would handle if there is no one strip
#(as next loop will not be entered)
already_measured= 0 #keeps track if next one strip is already measured.
#saves time in the loop
while i<len(nums):
#get the next strip
if already_measured == 0:
one=NextStripLen(nums,i)
else:
one=already_measured
already_measured=0 #reset
#get the next zero strip
zero=NextStripLen(nums,i+one)
if zero==1:
#count the next one strip as well
already_measured=NextStripLen(nums, i+one+zero)
cur=one + zero + already_measured
elif zero == 0:
#reached end.
cur=one
#borrow one more from previous strip of zero if it exists
if i!=0:
cur+=1
else:
#borrow one zero from the next strip
cur=one+1
longest=max(longest,cur)
i= i+ one + zero
return longest
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment