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
.
public int maxProduct(int[] A) {
int n=A.length;
if (n==0) return 0;
int max = 1, min = 1;
int res = Integer.MIN_VALUE;
for (int i=0;i<n;i++) {
if (A[i] > 0) {
max *= A[i];
min *= A[i];
res = Math.max(res,max);
} else if (A[i] == 0) {
res = Math.max(res,0);
max = 1;
min = 1;
} else {
res = Math.max(res,min*A[i]);
int oldmax = max;
max = Math.max(1,min*A[i]);
min = oldmax*A[i];
}
}
return res;
}