Python solution using two pointers beats 97%


  • 0
    B
    class Solution(object):
        def findMaxConsecutiveOnes(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums: return 0
            l=r = -1 # locations for the recent two zeros
            res = 0
            # loop to find the first zero
            for i in range(len(nums)):
                if nums[i] == 0:
                    r = i
                    res = i+1
                    break
            # if no zeros in the array, return the length
            if r == -1: return len(nums)
            dum = r
            
            for i in range(dum+1,len(nums)):
                if nums[i] == 0:
                    res = max(res,i-l-1)
                    l,r=r,i
            #case where there might be continue ones at the end
            if r!=len(nums)-1:
                res = max(res,len(nums)-1-l)
            return res
    

    41 / 41 test cases passed
    Runtime: 82 ms


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.