题目链接:https://leetcode.cn/problems/maximum-product-subarray/
难度:中等
描述:
给你一个整数数组 nums
,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
测试用例的答案是一个 32-位 整数。
子数组 是数组的连续子序列。
提示:1 <= nums.length <= 20000
-10 <= nums[i] <= 10
题解
class Solution:
def maxProduct(self, nums: List[int]) -> int:
ret = nums[0]
temp_max = nums[0]
temp_min = nums[0]
for i in range(1, len(nums)):
if nums[i] < 0:
temp_max, temp_min = temp_min, temp_max
temp_max = max(nums[i], nums[i] * temp_max)
temp_min = min(nums[i], nums[i] * temp_min)
else:
temp_max = max(nums[i], nums[i] * temp_max)
temp_min = min(nums[i], nums[i] * temp_min)
ret = max(ret, temp_max)
return ret