思路一:求解长度为n的区间内连续子数组的最大乘积,可以先求解前n-1个数组成的数组内的连续子数组的最大乘积,再考虑由第n个数组成的连续子数组中的乘积和前n-1个乘积中更大的,作为最终结果,代码如下:
class Solution:
def maxProduct(self, nums: List[int]) -> int:
size = len(nums)
res = [0] * size
res[0] = nums[0]
for i in range(1, size):
res[i] = max(res[i-1], nums[i])
for j in range(i-1, -1, -1):
nums[j] *= nums[i]
res[i] = max(res[i], nums[j])
return res[-1]
思路二:动态规划,维护以当前位置元素结尾的连续子数组的最大乘积和最小乘积,最终结果是这些最大乘积中最大的值
class Solution:
def maxProduct(self, nums: List[int]) -> int:
size = len(nums)
if size == 0: return 0
fmax = nums[0]
fmin = nums[0]
res = nums[0]
for i in range(1, size):
tmp1 = min(nums[i], fmax * nums[i], fmin * nums[i])
tmp2 = max(nums[i], fmax * nums[i], fmin * nums[i])
fmin = tmp1
fmax = tmp2
res = max(res, fmax)
return res