Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.
Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.
这道题让我们求一个数组乘积最大的子数组,看到这类题目的第一个想法便是用动态规划,答案也确实用的是这种方法,与求一个数组和最大的子数组不同,乘积最大需要考虑的情况更加复杂,因为当遇到0值时,子数组的乘积为0,遇到负数时,子数组的乘积会变号,因此我们在遍历整个数组时需要记录数组中的最大值与最小值,且每次都要记录下包含当前值的乘积最大和最小值。
C++
int maxProduct(vector<int>& nums) {
int res = nums[0];
int maxpro = nums[0];
int minpro = nums[0];
for(int i = 1;i < nums.size();++i)
{
int t1 = maxpro*nums[i];
int t2 = minpro*nums[i];
maxpro = max(max(t1,t2),nums[i]);
minpro = min(min(t1,t2),nums[i]);
res = max(maxpro,res);
}
return res;
}