[leetcode]Maximum Product Subarray @ Python

原題地址:https://oj.leetcode.com/problems/maximum-product-subarray/spa

解題思路:主要須要考慮負負得正這種狀況,好比以前的最小值是一個負數,再乘以一個負數就有可能成爲一個很大的正數。code

代碼:blog

class Solution:
    # @param A, a list of integers
    # @return an integer
    def maxProduct(self, A):
        if len(A) == 0:
            return 0
        min_tmp = A[0]
        max_tmp = A[0]
        result = A[0]
        for i in range(1, len(A)):
            a = A[i] * min_tmp
            b = A[i] * max_tmp
            c = A[i]
            max_tmp = max(max(a,b),c)
            min_tmp = min(min(a,b),c)
            result = max_tmp if max_tmp > result else result
        return result
        
相關文章
相關標籤/搜索