leetcode 152. 乘积最大子序列

给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。

示例 1:

输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。

示例 2:

输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#dp transfer
#max_local = max(max(max_local_pre*nums[i],nums[i]),min_local_pre*nums[i])
#min_local = min(min(max_local_pre*nums[i],nums[i]),min_local_pre*nums[i])
#max_global = max(max_local,max_global_pre)
if not nums:return 0
max_local = nums[0]
min_local = nums[0]
max_global = nums[0]
for i in range(1,len(nums)):
max_local_pre= max_local
max_local = max(max(max_local*nums[i],nums[i]),min_local*nums[i])
min_local = min(min(max_local_pre*nums[i],nums[i]),min_local*nums[i])
max_global = max(max_local,max_global)
return max_global