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
.
Solution in C++: maximum subarray的扩展
class Solution {
public:
int maxProduct(vector<int>& nums) {
if(nums.size()==0) return INT_MIN;
int opj_max[nums.size()];
int opj_min[nums.size()];
opj_max[0] = nums[0];
opj_min[0] = nums[0];
int maxp = nums[0];
int minp = nums[0];
for(int i=1; i<nums.size(); i++){
opj_max[i] = max(max(nums[i], nums[i]*opj_max[i-1]), nums[i]*opj_min[i-1]);
maxp = max(opj_max[i], maxp);
opj_min[i] = min(min(nums[i], nums[i]*opj_min[i-1]), nums[i]*opj_max[i-1]);
}
return maxp;
}
};
因为有正负数,负数和负数相乘可能得到更大值,所以另设一个数组保存min值,这样如果nums[i]是负数,利用min值就可以求出该位最大值。