题目:
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
.
思路:1,常规思路从头和尾分别相乘,保存最大积,遇到0就置1;
2.动态规划:如果是求最大和的话,只需要保存当前最大值和全局最大值就行;相乘可能出现偶数个负数,结果会不定,所以需要还保存一个当前最小值,因为乘除法可交换性,所以不用在意位置。一开始写的时候只想到找负数的个数去了。动态规划是极好的,核心是写出正确的状态方程。
#define MAX(x,y) ((x)>(y)?(x):(y))
#define MIN(x,y) ((x)<(y)?(x):(y))
class Solution {
public:
int maxProduct(vector<int>& nums)
{
int n=nums.size();
if (n <= 0)
return 0;
if (n == 1)
return nums[0];
int max_local = nums[0];
int min_local = nums[0];
int global = nums[0];
for (int i = 1; i != n; ++ i) {
int max_copy = max_local;
max_local = MAX(MAX(nums[i] * max_local, nums[i]), nums[i] * min_local);
min_local = MIN(MIN(nums[i] * max_copy, nums[i]), nums[i] * min_local);
global = MAX(global, max_local);
}
return global;
}
};