给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
测试用例的答案是一个 32-位 整数。
示例 1:
输入: nums = [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: nums = [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
和第 19 题类似。
考虑到是乘积,存在 负负得正的情况,所以也需要存储当前乘积最小值 min 以便下一次使用。 假设上一次循环的乘积最小值是 min,最大值是 max 遍历数组,每次求出当前元素和 min 和 max 的乘积, 在 nums[i], nums[i] * min, nums[i] * max 三个数中求出新的 min 和 max 结束本次循环之前用 max res, 更新一下结果。
var maxProduct = function (nums) {
let res = nums[0];
let min = nums[0]; // 最小乘积
let max = nums[0]; // 最大乘积
let tempMin = nums[0]; // 当前变量 与上一次循环 min 的乘积
let tempMax = nums[0]; // 当前变量与上一次循环 max 的乘积
for(let i = 1; i < nums.length; i++) {
tempMin = min * nums[i];
tempMax = max * nums[i];
min = Math.min(tempMin, tempMax, nums[i]); // 得到当前元素的最小乘积
max = Math.max(tempMin, tempMax, nums[i]); // 得到当前元素的最大乘积
res = Math.max(max, res); // 更新结果
}
return res;
};