My simple Python Solution, 48ms beat 95%


  • 0
    A

    Two variables to record the max positive value and min negative value for current position

    class Solution(object):
        def maxProduct(self, nums):
            """
            :type nums: List[int]
            :rtype: int
            """
            if not nums:
                return 0
            if len(nums)==1:
                return nums[0]
            l = len(nums)
            p,n,mx = 0,0,nums[0]
            if nums[0]>0:
                p= nums[0]
            else:
                n = nums[0]
            for i in range(1,l):
                if nums[i]>0:
                    p,n = max(p*nums[i],nums[i]),n*nums[i]
                    
                else:
                    p,n = n*nums[i],min(p*nums[i],nums[i])
                mx = max(mx,p)
            return mx

Log in to reply
 

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