题目:
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 size = nums.size(), res = INT_MIN;
if (size == 1)return nums[0];
vector<int> neg(size + 1, INT_MAX), pos(size + 1, INT_MIN);
neg[0] = pos[0] = 1;
for (int i = 0; i<size; ++i) {
neg[i + 1] = min(neg[i] * nums[i], pos[i] * nums[i]);
neg[i + 1] = min(neg[i + 1], nums[i]);
pos[i + 1] = max(neg[i] * nums[i], pos[i] * nums[i]);
pos[i + 1] = max(pos[i + 1], nums[i]);
res = max(neg[i + 1], res);
res = max(pos[i + 1], res);
}
return res;
}
};