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.
LeetCode:链接
本题要求连续子数组的最大乘积,maxvalue[i]表示以a[i]a[i]为结尾的子数组中最大乘积,同时维护一个全局最大值globalmax,记录maxvalue[i]中的最大值。与求子数组的最大和不同的是,还需要记录子数组最小乘积minvalue[i],因为可能会出现 负 × 负 = 正的情况。并且最大最小乘积只可能出现在 (maxvalue[i−1]×a[i],minvalue[i−1]×a[i],a[i])三者之间。
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