Easy to understand Python solution in O(n) time and O(1) space!


  • 0
    L
    class Solution(object):
        def maxProduct(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            maxsofar, prevmax, prevmin, currmax, currmin = nums[0],nums[0], nums[0],nums[0], nums[0]
            for i in range(1, len(nums)):
                if nums[i]>0:
                    currmax = max(nums[i], prevmax*nums[i])
                    currmin = min(nums[i], prevmin*nums[i])
                else:
                    currmax = max(nums[i], prevmin*nums[i])
                    currmin = min(nums[i], prevmax*nums[i])
                maxsofar = max(maxsofar, currmax)
                prevmax, prevmin = currmax, currmin
            
            return maxsofar
                
    

Log in to reply
 

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