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.
分析:
题目要求连续字串的最大乘积。没想法,借鉴了别人的。
累乘的结果有三种:1. 正数(正数* 正数 ,负数*负数); 2. 负数( 正数*负数); 3. 零。
所以我们在求最大值时,要去保存之前的最大值和最小值。同时要将保存的最大值/最小值*当前值,和当前值做比较找到最大值。
def maxProduct(nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums)==0:
return
maxpre = minpre = res = nums[0]
for i in range(1, len(nums)):
maxcur = max(max(maxpre*nums[i], minpre*nums[i]), nums[i])
mincur = min(min(maxpre*nums[i], minpre*nums[i]), nums[i])
res = max(maxcur, res)
maxpre = maxcur
minpre = mincur
return res