Problem:
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
.
Solution:
See some examples first.
public class Solution {
public int maxProduct(int[] A) {
if (A.length == 1) {
return A[0];
}
int result = A[0]; // must be assigned A[0] (but not Integer.VALUE_MIN) in case A[0] is the largest product.
int maxProduct = A[0]; // local maxProduct
int minProduct = A[0]; // local minProduct
for (int i = 1; i < A.length; i++) {
int tmp = maxProduct;
maxProduct = Math.max(Math.max(maxProduct * A[i], A[i]), minProduct * A[i]);
minProduct = Math.min(Math.min(tmp * A[i], A[i]), minProduct * A[i]);
if (maxProduct > result) {
result = maxProduct;
}
}
return result;
}
}