Simple Python. O(n) Time


  • 0
    L

    Its a two step process.
    1- First build a count array, representing the count of continuous ones.
    2- Iterate on the count array to find the max. sum that you can find of two consecutive counts.

        def findMaxConsecutiveOnes(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            maxLen = 0
            countArray = [ ]
            count =0
            for i in range(0, len(nums)):
                if nums[i]==1:
                    count+=1
                else:
                    countArray.append(count)
                    count =0
            countArray.append(count)
            for i in range(1, len(countArray)):
                s=countArray[i-1]+countArray[i]
                maxLen = max(s, maxLen)
            if len(countArray)==1:
                return countArray[0]
            else:
                return maxLen+1
    

Log in to reply
 

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