Given an integer array nums
, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4] Output: 6 Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1] Output: 0 Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
这道题主要考虑的是负数和0:
如果有0则跳过重新计算乘积即可。
如果一串数字中有负数偶数个的话没有影响,还是照常计算即可。
如果一串数字中有奇数个负数,则把这串数字分成两部分,每部分负数为偶数个即可。比如1234-5678就可以看做在1234和678中取最大值;比如123-4-5-678就可以看做在123-4-5和-5-678中取最大值。
所以可以分别从前到后相乘,再从后到前相乘,取两种方法得到的最大值即可。
class Solution:
def maxProduct(self, nums: List[int]) -> int:
dp = nums[::-1]
for i in range(1,len(nums)):
if dp[i-1]!=0:
dp[i] = dp[i]*dp[i-1]
if nums[i-1]!=0:
nums[i] = nums[i]*nums[i-1]
return max(nums+dp)
还有简单的写法:
class Solution:
def maxProduct(self, nums: List[int]) -> int:
dp = nums[::-1]
for i in range(1,len(nums)):
dp[i] *= dp[i-1] or 1
nums[i] *= nums[i-1] or 1
return max(nums+dp)