乘积最大子数组
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
#空间复杂度O(N)
# max_dp, min_dp = [nums[0]] * len(nums), [nums[0]] * len(nums)
# for i in range(1, len(nums)):
# max_dp[i] = max(max_dp[i-1] * nums[i], max(nums[i], min_dp[i-1] * nums[i]))
# min_dp[i] = min(min_dp[i-1] * nums[i], min(nums[i], max_dp[i-1] * nums[i]))
# return max(max_dp)
#优化空间
min_n, max_n, res = nums[0], nums[0], nums[0]
for i in range(1, len(nums)):
tem_max = max_n
tem_min = min_n
max_n = max(max_n * nums[i], max(tem_min * nums[i], nums[i]))
min_n = min(min_n * nums[i], min(tem_max * nums[i], nums[i]))
res = max(max_n, res)
return res