本题题目要求如下:
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
.
现在介绍下本题的做法。。。
本题设定两个vector,一个存储以该点为终点的最小值(绝对值最大的负值),另外一个存储以该点为终点的最大值。。
比如本题的例子[2,3,-2,4]
运行结果如下:
- 初始化:pos[0,0,0,0], neg[0,0,0,0]
- 对2处理: pos[2,0,0,0], neg[0,0,0,0]
- 对3处理: pos[2,6,0,0], neg[0,0,0,0] // 2 * 3 = 6
- 对-2处理: pos[2,6,0,0], neg[0,0,-12,0] // 6 * -2 = -12
- 对4处理: pos[2,6,0,0], neg[0,0,-12,-24]
pos[i] = max(pos[i-1]*num[i], neg[i-1]*num[i], num[i])
neg[i] = min(pos[i-1]*num[i], neg[i-1]*num[i], num[i])
代码如下:
class Solution {
public:
int maxProduct(vector<int>& nums) {
vector<int> pos(nums.size(), 0);
vector<int> neg(nums.size(), 0);
if (nums[0] > 0) {
pos[0] = nums[0];
}
else {
neg[0] = nums[0];
}
int max_item = nums[0];
for (int i = 1; i < nums.size(); ++i) {
pos[i] = max(pos[i-1]*nums[i], max(nums[i], neg[i-1]*nums[i]));
neg[i] = min(pos[i-1]*nums[i], min(nums[i], neg[i-1]*nums[i]));
if (pos[i] > max_item)
max_item = pos[i];
}
return max_item;
}
};