题目描述:
给你一个整数数组 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
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解:
class Solution {
public:
int maxProduct(vector<int>& nums)
{
int n = nums.size();
if(n == 0)
return 0;
int dpmin = nums[0];
int dpmax = nums[0];
int res = nums[0];
for(int i=1;i<n;++i)
{
int temp1 = dpmin;
int temp2 = dpmax;
dpmin = min(nums[i],min(nums[i]*temp1,nums[i]*temp2));
dpmax = max(nums[i],max(nums[i]*temp1,nums[i]*temp2));
res = max(res,dpmax);
}
return res;
}
};
解题思路:、
因为是乘法运算,所以维护一个连续最大乘积序列,和一个连续最小乘积序列,注意要先保存dpmin 和 dpmax,因为后序要更改,这也是动态规划中经常要注意的问题。