题目
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.
题目要求
给定一个数组,求其一个子数组,使得子数组各个元素的乘积最大。
解题思路
此题借鉴了南郭子綦的解题思路。
借此题需要考虑的是乘积中的负负得正的技巧。所以需要记录下当前的最小值,因为最小值可能为一个负数,负数再乘以一个负数可能得到一个很大的数。
代码
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) == 0:
return 0
min_tmp = nums[0]
max_tmp = nums[0]
res = nums[0]
for i in range(1,len(nums)):
a = nums[i] * min_tmp
b = nums[i] * max_tmp
c = nums[i]
min_tmp = min(a,min(b,c))
max_tmp = max(a,max(b,c))
if res < max_tmp: res = max_tmp
return res