Python One-pass O(n) time O(1) space generalized solution for follow up


  • 0
    class Solution(object):
        def findMaxConsecutiveOnes(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            ans = count = lastCount = 0
            for num in nums:
                if num == 1:
                    count += 1
                else:
                    count = count - lastCount + 1
                    lastCount = count 
                ans = max(ans, count)
            return ans
    

    For follow-up:

    class Solution(object):
        def __init__(self):
            self.ans = 0
            self.count = 0
            self.lastCount = 0
            
        def findMaxConsecutiveOnes(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            for num in nums:
                self.readNum(num)    # stream the input
            return self.ans
        
        def readNum(self, num):
            """
            :type nums: int
            """
            if num == 1:
                self.count += 1
            else:
                self.count = self.count - self.lastCount + 1
                self.lastCount = self.count 
            self.ans = max(self.ans, self.count)
    

Log in to reply
 

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