题解 | 连续子数组的最大乘积
连续子数组的最大乘积
https://www.nowcoder.com/practice/abbec6a3779940aab2cc564b22d36859
import java.util.*;
public class Solution {
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param nums int整型一维数组
* @return int整型
*/
public int maxProduct (int[] nums) {
// write code here
if (nums == null || nums.length == 0) {
return 0;
}
// 初始化:当前最大值、当前最小值和全局最大值都设为数组的第一个元素
int curMax = nums[0];
int curMin = nums[0];
int res = nums[0];
// 从第二个元素开始遍历
for (int i = 1; i < nums.length; i++) {
int num = nums[i];
// 因为在计算新的 curMax 时会改变旧的 curMax 的值,
// 而计算 curMin 时还需要用到旧的 curMax,所以需要先存到一个临时变量中。
int tempMax = curMax;
// 更新以当前元素结尾的最大值和最小值
curMax = Math.max(num, Math.max(tempMax * num, curMin * num));
curMin = Math.min(num, Math.min(tempMax * num, curMin * num));
// 更新全局最大答案
res = Math.max(res, curMax);
}
return res;
}
}
