Share my python solution with recursion


  • 0
    C

    from operator import mul

    class Solution(object):
    def maxProduct(self, nums):
    """
    :type nums: List[int]
    :rtype: int
    """
    if len(nums)==1:
    return nums[0]

        for i in xrange(len(nums)):
            if nums[i]==0:
                if i==0:
                    return max(0,self.maxProduct(nums[1:]))
                if i==len(nums)-1:
                    return max(0,self.maxProduct(nums[:-1]))
                return max(self.maxProduct(nums[:i]),0,self.maxProduct(nums[i+1:]))
        
        a=-1 #index of first negative number
        b=-1 #index of last negative number
        c=0 #number of negative numbers
        for i in  xrange(len(nums)):
            if nums[i]<0:
                b=i
                c+=1
                if a==-1:
                    a=i
        
        if c%2==0:
            return reduce(mul,nums)
        else:
            if len(nums[a+1:])>0 and len(nums[:b])>0:
                return max(reduce(mul,nums[a+1:]),reduce(mul,nums[:b]))
            elif len(nums[a+1:])>0:
                return reduce(mul,nums[a+1:])
            else:
                return reduce(mul,nums[:b])

Log in to reply
 

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