Maximum Product Subarray
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 class Solution {
public int maxProduct(int[] A) {
if(A == null || A.length == 0) return 0;
int result = A[0];
int pos = Math.max(0, A[0]);
int neg = Math.min(0, A[0]);
for(int i = 1; i < A.length; i++) {
if(A[i] == 0) {
pos = 0;
neg = 0;
} else if(A[i] > 0) {
pos = Math.max(A[i], pos * A[i]);
neg = neg * A[i];
} else {
int old_pos = pos;
pos = neg * A[i];
neg = Math.min(A[i], old_pos * A[i]);
}
result = Math.max(result, pos);
}
return result;
}
}

浙公网安备 33010602011771号