乘积最大子序列
给定一个整数数组 nums
,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1] 输出: 0 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
class Solution:
def maxProduct(self, nums: List[int]) -> int:
if len(nums)==1:
return nums[0]
posmax,negmax=0,0
res = nums[0]
for i in range(len(nums)):
tmpposmax = posmax
tmpnegmax = negmax
posmax = max(nums[i], max(tmpposmax*nums[i], tmpnegmax*nums[i]))
negmax = min(nums[i], min(tmpposmax*nums[i], tmpnegmax*nums[i]))
res = max(res,posmax)
return res
class Solution {
public:
int maxProduct(vector<int>& nums) {
if(nums.size()==1)
return nums[0];
int posmax=0,negmax=0;
int res = nums[0];
int tmpposmax,tmpnegmax,tmp;
for(int i=0;i<nums.size();i++){
tmpposmax = posmax*nums[i];
tmpnegmax = negmax*nums[i];
tmp = max(tmpposmax,tmpnegmax);
posmax = max(nums[i], tmp);
tmp = min(tmpposmax,tmpnegmax);
negmax = min(nums[i], tmp);
res = max(res,posmax);
}
return res;
}
};
问题&思路:
- 每读一个数就计算当前的最大正乘积和最小的负乘积,然后更新。因为负负得正。当前乘积最大子序列可能是因为之前一个最小的负乘积和当前数刚好是一个负数乘来的。