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,注意负数与负数相乘变成正数。
代码
int maxProduct(vector<int>& nums) {
int max_ending_here_positive = nums[0]>0 ? nums[0] : 1;
int max_ending_here_negative = nums[0]<0 ? nums[0] : 1;
int max_so_far=nums[0];
for(int i=1;i<nums.size();i++){
int mp=max_ending_here_positive;
int mn=max_ending_here_negative;
int max_tmp = max(mp*nums[i], mn*nums[i]);
max_ending_here_positive = max(max_tmp, 1);
max_ending_here_negative = min(min(mp*nums[i], mn*nums[i]), 1);
max_so_far = max(max_so_far,max_tmp);
}
return max_so_far;
}