题目:
给你一个整数数组 nums ,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字)。
思路:
考虑数组中为负数的情况。
程序:
class Solution:
def maxProduct(self, nums: List[int]) -> int:
length = len(nums)
if length <= 0:
return 0
if length == 1:
return nums[0]
result = nums[0]
auxiliary_max = [0] * length
auxiliary_min = [0] * length
auxiliary_max[0] = nums[0]
auxiliary_min[0] = nums[0]
for index in range(1, length):
if nums[index] >= 0:
auxiliary_max[index] = max(auxiliary_max[index - 1] * nums[index], nums[index])
auxiliary_min[index] = min(auxiliary_min[index - 1] * nums[index], nums[index])
else:
auxiliary_max[index] = max(auxiliary_min[index - 1] * nums[index], nums[index])
auxiliary_min[index] = min(auxiliary_max[index - 1] * nums[index], nums[index])
result = max(result, auxiliary_max[index])
return result