题目描述
找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。
例如, 给定序列 [2,3,-2,4],
其中乘积最大的子序列为 [2,3] 其乘积为 6。
解题思路
public int maxProduct(int[] A) {
if (A == null || A.length == 0) {
return 0;
}
//由于可能存在负数,所以必须同时存储最大值和最小值
int max = A[0],
min = A[0],
result = A[0]; //存储最后的结果
for (int i = 1; i < A.length; i++) {
int temp = max;
max = Math.max(Math.max(max * A[i], min * A[i]), A[i]);
min = Math.min(Math.min(temp * A[i], min * A[i]), A[i]);
if (max > result) {
result = max;
}
}
return result;
}