最大子数组乘积

最大子数组乘积
https://oj.leetcode.com/problems/maximum-product-subarray/

分类讨论各个情况,对A=[a1,a2,a3....an]
①.无0,无或偶数个负数,result=a1*a2*a3*...*an
②.无0,奇数个负数,假设首个负数在i号位置,最后负数在j号位置,则result=max(a1*a2*...*a(j-1),a(i+1)*a(i+2)*...*an)
③.有0,以0为界,对数组分割,转换成①②问题求解。

class Solution:
    # @param A, a list of integers
    # @return an integer
    def maxProduct(self, A): 
        if not A: 
            return 0
        if len(A)==1:
            return A[0]
        zeroPos,minusPos=[],[]
        for pos,n in enumerate(A):
            if n==0:
                zeroPos.append(pos)
            elif n<0:
                minusPos.append(pos)
        if not zeroPos:
            if len(minusPos)%2==0:
                result=1
                for i in A:
                    result*=i
                return result
            else:
                first,last=minusPos[0],minusPos[-1]
                leftMul,rightMul=1,1
                for i in A[first+1:]:
                    leftMul*=i
                for i in A[0:last]:
                    rightMul*=i
                return max(leftMul,rightMul)
        else:
            result=0
            prePos=-1
            for pos in zeroPos:
                result=max(result,self.maxProduct(A[prePos+1:pos]))
                prePos=pos
            result=max(result,self.maxProduct(A[prePos+1:]))
            return result

s=Solution()
print s.maxProduct([0,3,0,-4]


你可能感兴趣的:(最大子数组乘积)