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)
{
int ret=A[0];
vector<int> maxValue(n,0);
vector<int> minValue(n,0);
for(int i=0;i<n;i++)
{
if(i==0)
{
maxValue[i]=minValue[i]=A[i];
}
else
{
minValue[i]=min(A[i],min(A[i]*maxValue[i-1],A[i]*minValue[i-1]));
maxValue[i]=max(A[i],max(A[i]*maxValue[i-1],A[i]*minValue[i-1]));
ret=max(ret,maxValue[i]);
}
}
return ret;
}
};