【LeetCode】【152. Maximum Product Subarray】(python版)

Description:
Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

思路:
本题要求连续子数组的最大乘积,思路与求连续子数组的最大和相似,都是采用动态规划, m a x v a l u e [ i ] 表示 a [ i ] 为结尾的子数组中最大乘积,同时维护一个全局最大值 g l o b a l m a x ,记录 m a x v a l u e [ i ] 中的最大值。与求子数组的最大和不同的是,还需要维记录子数组最小乘积 m i n v a l u e [ i ] ,因为可能会出现 负 × 负 = 正的情况。并且最大最小乘积只可能出现在
( m a x v a l u e [ i 1 ] × a [ i ] , m i n v a l u e [ i 1 ] × a [ i ] , a [ i ] ) 三者之间。

下面以[2,3,-2,4]演示求解过程

子数组末尾数字 最大乘积 最小乘积
2 2 2
3 6 3
-2 -2 -12
4 4 -48

代码实现如下:

    class Solution(object):
    def maxProduct(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        maxvalue = minvalue = nums[0]
        globalmax = nums[0]
        for i in range(1, len(nums)):
            lastmax = maxvalue
            maxvalue = max(minvalue * nums[i], lastmax * nums[i], nums[i])
            minvalue = min(minvalue * nums[i], lastmax * nums[i], nums[i])
            globalmax = max(globalmax, maxvalue)
        return globalmax

猜你喜欢

转载自blog.csdn.net/qq_20141867/article/details/80995181