找出一个序列中乘积最大的连续子序列
边乘边找,维护pre1和pre2。
-
pre1
大于0的前缀乘积的最小值 -
pre2
小于0的前缀乘积的最大值 -
对于序列中的零
不乘,且重置累乘结果now,pre1和pre2。
每次更新ans。
152. 乘积最大子序列
class Solution {
public:
int maxProduct(vector<int>& nums) {
int tip=nums.size();
int now=1;
int pre1=1;
int pre2=-1e9;
int ans=nums[0];
for (int i=0;i<tip;i++){
//对0的特殊处理,不乘
if (nums[i]==0){
now=1;
pre1=1;
pre2=-1e9;
continue;
}
now*=nums[i];
if (i>0){
if (now>0) ans=max(ans,now/pre1);
else{
ans=max(ans,now/pre2);
}
}
if (now>0) pre1=min(pre1,now);
else if (now<0){
pre2=max(pre2,now);
}
}
return ans;
}
};