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;
}
};