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
.
参考了 @ych_ding 的方法,比我原来的简洁太多。
public class Solution {
public int maxProduct(int[] A) {
if (A.length == 0) return 0;
if (A.length == 1) return A[0];
int min = A[0];
int max = A[0];
int res = max;
for (int i = 1; i < A.length; i++) {
int tmp1 = min * A[i];
int tmp2 = max * A[i];
min = Math.min(A[i], Math.min(tmp1, tmp2));
max = Math.max(A[i], Math.max(tmp1, tmp2));
res = Math.max(max, res);
}
return res;
}
}