题目描述:
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4]
,
the contiguous subarray [2,3]
has the largest product = 6
.
Subscribe to see which companies asked this question
即: 给定一个数组, 计算最大的连续乘积。
如: 给定[2,3,-2,4] 时,最大乘积为2*3 = 6
给定[-2, 3, -4] 时, 最大乘积为 -2*3*-4
因此,因此遇到负数时,不能简单认为是最小的,如果后面还有负数的话,会使计算错误。
以第i个数结尾的最大的乘积计算如下:
1. 如果第i个数大于0, 则max[i] = max(max[i-1]*nums[i], nums[i])
2. 如果第i个数小于0, 则max[i] = min(min[i-1]*nums[i], nums[i])
因此我们需要记录 以第i个数结尾的最大和最小乘积。
以第i个数结尾的最小乘积计算如下:
1. 如果nums[i] 大于0, 则min[i] = min(min[i-1]*nums[i], nums[i])
2. 如果nums[i] 小于0, 则min[i] = max(max[i-1]*nums[i], nums[i])
代码如下:
1 class Solution(object): 2 def maxProduct(self, nums): 3 """ 4 :type nums: List[int] 5 :rtype: int 6 """ 7 ln = len(nums) 8 maxPro = [0]*(ln+1) 9 minPro = [0]*(ln+1) 10 maxPro[0] = 1 11 minPro[0] = 1 12 for i in range(0, ln): 13 if nums[i] >= 0: 14 maxPro[i+1] = max(maxPro[i]*nums[i], nums[i]) 15 minPro[i+1] = min(minPro[i]*nums[i], nums[i]) 16 else: 17 minPro[i+1] = min(maxPro[i]*nums[i], nums[i]) 18 maxPro[i+1] = max(minPro[i]*nums[i], nums[i]) 19 return max(maxPro[1:])
时间: 2024-11-06 09:47:59