版权声明:转载请和我说。 https://blog.csdn.net/u010929628/article/details/89635312
题目内容
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.
题目思路
这道题目可以采用动态规划的思想。对于以nums[i]为参与者的连乘结果来说,最大的数值可能是nums[i]本身,可能是它乘以前面的最小值(负负为正),也可能是他自己乘以最大值;而最小值可能是它自己,可能是它乘以之前的最小值,它乘以之前的最大值(异号)。然后在算出当前的最大值和之前的最大值哪个更大就可以了。
程序代码
class Solution(object):
def maxProduct(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
maxv,minv,res=nums[0],nums[0],nums[0]
for i in range(1,len(nums)):#其中maxv,minv都是动态规划中以nums[i]为参与者情况下的最大最小数值,并确定一个全局最大值
lstv=maxv#因为maxv接下来会更新,所以要有一个替补
maxv,minv=max(nums[i],nums[i]*lstv,nums[i]*minv),min(nums[i],nums[i]*lstv,nums[i]*minv)
res=max(maxv,res)
return res