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
.
题目要求找连续子数组乘积最大时的乘积。类比于求连续子数组和最大的和。
对于连续子数组,用动态规划,从数组头0开始动态规划,需要记录当前i节点的全局最大值globalMax[i]以及包含结点i的局部最大值localMax[i]。对于包含节点i的局部最大值,是求包含节点i-1的局部最大值localMax[i-1]+A[i]与A[i]看哪个最大。对于全局最大值globalMax[i],是找globalMax[i-1]与localMax[i]看哪个最大,转移方程如下:
localMax[i] = max(localMax[i-1]+A[i],A[i]);
globalMax[i] = max(globalMax[i-1],localMax[i]);
对于乘法,由于需要考虑负负得真的情况,需要同时记录动态到当前i节点时的局部最小值和局部最大值,因为局部最小值*一个负数,可能变为局部最大值,而局部最大值*一个负数,可能变为局部最小值。全局最大值不变,为i-1节点的全局最大值与i节点的局部最大值取最大者。转移方程如下:
minLocal[i] = min( min(minLocal[i-1]*A[i],maxLocal[i-1]*A[i]), A[i]);
maxLocal[i] = max( max(minLocal[i-1]*A[i], maxLocal[i-1]*A[i]), A[i]);
globalMax[i] = max(maxLocal[i], globalMax[i-1]);
有限层转移,可以用有限变量来迭代转移状态,代码如下:
class Solution {
public:
int maxProduct(int A[], int n) {
if(n<=0)return 0;
int minLocal,maxLocal,preMinLocal,globalMax;
minLocal = A[0];maxLocal = A[0];globalMax = A[0];
for(int i=1;i<n;i++){
preMinLocal = minLocal;
minLocal = min(min(minLocal*A[i],maxLocal*A[i]),A[i]);
maxLocal = max(max(maxLocal*A[i],preMinLocal*A[i]),A[i]);
globalMax = max(maxLocal,globalMax);
}
return globalMax;
}
};
备注: 动态规划,最核心的目标是找转移方程。