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
.
很显然是一个动态规划的问题,找到递归表达式就可以了,考虑到会有负负相乘的问题,所以应该维持一个最大的值以及一个最小的值,递归表达式如下所示:
maxLocal[i + ] = max(max(maxLocal[i] * nums[i + ], minLocal[i] * nums[i + ]), nums[i + ]);
minLocal[i + ] = min(min(maxLocal[i] * nums[i + ], minLocal[i] * nums[i + ]), nums[i + ]);
maxGlobal[i + ] = max(maxGlobal[i], maxLocal[i + ]);
代码如下所示:
class Solution {
public:
int maxProduct(vector<int>& nums) {
int sz = nums.size();
if (sz == )return ;
if (sz == )return nums[];
int maxP, minP, a, b, ret;
ret = maxP = minP = a = b = nums[];
for (int i = ; i < sz; ++i){
a = max(maxP * nums[i], minP * nums[i]);
b = min(maxP * nums[i], minP * nums[i]);
maxP = max(a, nums[i]);
minP = min(b, nums[i]);
ret = max(maxP, ret);
}
return ret;
} };
java版本的如下所示,注意使用两个中间变量的原因是防止maxVal先直接更新了之后又被minVal所误用:
public class Solution {
public int maxProduct(int[] nums) {
int maxVal, minVal, ret, tmpMax, tmpMin;
maxVal = minVal = ret = tmpMax = tmpMin = nums[0];
for(int i = 1; i < nums.length; ++i){
tmpMax = Math.max(maxVal * nums[i], minVal * nums[i]);
tmpMin = Math.min(maxVal * nums[i], minVal * nums[i]);
maxVal = Math.max(tmpMax, nums[i]);
minVal = Math.min(tmpMin, nums[i]);
ret = Math.max(maxVal, ret);
}
return ret;
}
}