题目:Maximum Product Subarray
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
Find the contiguous subarray within an array (containing at least one number) which has the largest product.
For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.
这道题属于动态规划的题型,之前常见的是Maximum SubArray,现在是Product Subarray,不过思想是一致的。
而对于Product Subarray,要考虑到一种特殊情况,即负数和负数相乘:如果前面得到一个较小的负数,和后面一个较大的负数相乘,得到的反而是一个较大的数,如{2,-3,-7},所以,我们在处理乘法的时候,除了需要维护一个局部最大值,同时还要维护一个局部最小值,由此,可以写出如下的转移方程式:
max_copy[i] = max_local[i]
max_local[i + 1] = Max(Max(max_local[i] * A[i], A[i]), min_local * A[i])
min_local[i + 1] = Min(Min(max_copy[i] * A[i], A[i]), min_local * A[i])
对应代码如下:
class Solution {
public:
int maxProduct(vector<int>& nums) {
int size = nums.size();
if (size == 1) {
return nums[0];
}
int maxTemp = nums[0];
int minTemp = nums[0];
int maxSubs = nums[0];
int maxCopy = 0;
for (auto it = nums.begin() + 1; it != nums.end(); ++it) {
maxCopy = maxTemp;
maxTemp = max(max(maxTemp*(*it), *it), minTemp*(*it));
minTemp = min(min(maxCopy*(*it), *it), minTemp*(*it));
maxSubs = max(maxSubs, maxTemp);
}
return maxSubs;
}
private:
int max(int a, int b);
int min(int a, int b);
};
int Solution::max(int a, int b)
{
return (a > b) ? a : b;
}
int Solution::min(int a, int b)
{
return (a < b) ? a : b;
}