题目描述
给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
示例 1:
输入: [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路
由于存在负数,那么最大的数可能变最小的数,最小的数也可能变最大的数。所以设置两个变量now_max,now_min记录以num[i]为尾的子序列乘积的最大和最小值,当num[i]为负数,则先调换now_max和now_min的值,再计算此时的最大和最小值。
代码(c++)
class Solution {
public:
int maxProduct(vector<int>& nums) {
if(nums.size()==0) return 0;
int res=nums[0];
int now_max=nums[0];
int now_min=nums[0];
for(int i=1;i<nums.size();i++){
if(nums[i]<0) swap(now_max,now_min);
now_max=max(nums[i],nums[i]*now_max);
now_min=min(nums[i],nums[i]*now_min);
res=max(res,now_max);
}
return res;
}
};