Very short Python O(n) solution, beats 93%


  • 0
    M

    The trick is to do a pass over the list to track where each zero locates. Once done, count how many ones are there on both sides (to the left and to the right) of each zero. Finally, return the maximum count.

        def findMaxConsecutiveOnes(self, nums):
            if not nums: return 0
            zeros = [-1] + [i for i,n in enumerate(nums) if n == 0] + [len(nums)]
            
            if len(zeros) == 2: return len(nums)
            maxcnt = 0
            for i in range(1,len(zeros)-1):
                cnt = zeros[i+1] - zeros[i-1] - 1
                maxcnt = max(maxcnt, cnt)
            return maxcnt
    

Log in to reply
 

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