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(int A[], int n) {
if (n == 1) return A[0];
int pMax=A[0],nMax=A[0],m=A[0];
for(int i = 1; i < n; i++)
{
if(A[i]<0) swap(pMax,nMax);
pMax=max(pMax*A[i],A[i]);
nMax=min(nMax*A[i],A[i]);
m = max(pMax,m);
}
return m;
}
};
本文介绍了一种利用动态规划解决寻找数组中具有最大乘积的连续子数组的方法。通过一个示例数组 [2,3,-2,4] 的解析,展示了如何找到最大乘积子数组 [2,3] 的过程。
551

被折叠的 条评论
为什么被折叠?



