连续的处理很巧妙,借用了一个res处理,常看
class Solution:
def maxProduct(self, nums: List[int]) -> int:
# 存放到当前索引的最大值,最小值, 状态定义成二维的好做
# 不要搞dp = [[0, 0]] * 2里面的[0, 0] 就是一个了,变化会有干扰的, 是浅拷贝
dp = [[nums[0] for _ in range(2)] for _ in range(2)]
res = nums[0]
for i in range(1, len(nums)):
# -1 % 2 为 1,-1 // 2 为 -1
# x 先1 后0 然后循环 y 先0 后1 然后循环
x, y = i % 2, (i - 1) % 2
# dp[x][1] 放了到当前索引的乘积最小值, dp[x][0] 放了从起始索引到现在的乘积最大值,遇到负数就更新这个起始索引
# res放了到当前索引的最大值。
# 这个处理很牛,可以记住这种处理
dp[x][0] = max(dp[y][0] * nums[i], nums[i], dp[y][1] * nums[i])
dp[x][1] = min(dp[y][0] * nums[i], nums[i], dp[y][1] * nums[i])
res = max(dp[x][0], res)
return res