给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
示例 1:
输入: [2,3,-2,4] 输出: 6 解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: [-2,0,-1] 输出: 0 解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
维护三个变量:局部最大值,局部最小值,总最大值
class Solution {
public:
int maxProduct(vector<int>& nums)
{
int len = nums.size();
if(len <= 1)
{
return len == 0? 0 : nums[0];
}
int min_local = nums[0];
int max_local = nums[0];
int res = nums[0];
for(int i = 1; i < len; i++)
{
int temp = max_local;
max_local = max(max(max_local * nums[i], nums[i]), nums[i] * min_local);
min_local = min(min(min_local * nums[i], nums[i]), temp * nums[i]);
res = max(max_local, res);
}
return res;
}
};