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
.
C++代码实现:
int maxProduct(vector<int>& nums) {
if (nums.size() == 0){
return 0;
}
else if (nums.size() == 1){
return nums[0];
}
else{
int n = nums.size();
int *dp = new int[n];
int max = INT_MIN;
//迭代的方式去构建dp数组
for (int i = 0; i < n; i++){
if (nums[i] == 0){
dp[i] = 0;
//如果前一个是0的话,那么跳过一个数;
if (i + 1 < n){
dp[i + 1] = nums[i + 1];
if (dp[i + 1] > max){
max = dp[i + 1];
}
}
i++;
continue;
}
if (i == 0 || dp[i - 1] == 0){
dp[i] = nums[i];
}
else{
dp[i] = dp[i - 1] * nums[i];
}
if (dp[i]>max){
max = dp[i];
}
}
bool b = false;
int neg = 0;
for (int i = 0; i < n; i++){
if (dp[i] < 0 && !b){
b = !b;
neg = i;
}
else if (dp[i] == 0){
if (0 > max){
max = 0;
}
b = false;
}
else if (b){
if ((dp[i] / dp[neg]) > max){
max = dp[i] / dp[neg];
}
}
}
return max;
}
}
以上是一种dp的解法,只需要扫描一遍数组,将整个的计算结果存放在对应的dp数组中。0在乘法中作为一个特殊的数,我们当遇到0的时候要从0之后的数进行计算。