Python solution


  • 0
    H
    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]
            if 0 in nums:
                zind=nums.index(0)
                pl=self.maxProduct(nums[:zind])
                pr=self.maxProduct(nums[zind+1:])
                p=max(0,pl,pr)
                return p
            nl,nr=-1,-1
            p=1
            for i,j in enumerate(nums):
                p*=j
                if j<0:
                    if nl<0:
                        nl=i
                    nr=i
            if nl<0:
                return p
            if p>0:
                return p
            if not nr:
                return p/nums[0]
            if nl==len(nums)-1:
                return p/nums[-1]
            pl,pr=p,p
            for i in range(nl+1):
                pr/=nums[i]
            for i in range(nr,len(nums)):
                pl/=nums[i]
            return max(pl,pr)

Log in to reply
 

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