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怎么处理,参考最大子段和的思路,能影响以i结尾的结果无非是之前负最小和正最大。。。
import sys
class Solution:
def maxProduct(self, nums: List[int]) -> int:
mi,ma,res = 1,1,-sys.maxsize
for num in nums:
if (num<0):
mi,ma=ma,mi
ma = max(ma*num, num)
mi = min(mi*num, num)
res = max(ma,res)
return res

733

被折叠的 条评论
为什么被折叠?



