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
.
思路:用两个数组,一个存放整数乘积,一个存放负数乘积。
class Solution {
public:
int maxProduct(vector<int>& nums) {
int n = nums.size();
if (n == 0) return 0;
if (n == 1) return nums[0];
vector<int> pos(n, 0); //最大正数
vector<int> neg(n, 0); //最大负数
pos[0] = nums[0] > 0 ? nums[0] : 0;
neg[0] = nums[0] < 0 ? nums[0] : 0;
for (int i = 1; i < n; i++) {
if (nums[i] == 0) {
pos[i] = 0;
neg[i] = 0;
}
else if(nums[i]>0){
pos[i] = pos[i - 1] == 0 ? nums[i] : pos[i - 1] * nums[i];
neg[i] = neg[i - 1] == 0 ? 0 : neg[i-1] * nums[i];
}
else {
pos[i] = neg[i - 1] == 0 ? 0 : neg[i-1] * nums[i];
neg[i] = pos[i - 1] == 0 ? nums[i] : pos[i - 1] * nums[i];
}
}
int maxProduct = INT_MIN;
for (int i = 0; i < n; i++) {
maxProduct = maxProduct > pos[i] ? maxProduct : pos[i];
}
return maxProduct;
}
};