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.
思路:
本题要求连续子数组的最大乘积,思路与求连续子数组的最大和相似,都是采用动态规划,
表示以
为结尾的子数组中最大乘积,同时维护一个全局最大值
,记录
中的最大值。与求子数组的最大和不同的是,还需要维记录子数组最小乘积
,因为可能会出现 负 × 负 = 正的情况。并且最大最小乘积只可能出现在
三者之间。
下面以[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