题目
给你一个整数数组
nums
,请你找出数组中乘积最大的连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
示例
输入: [2,3,-2,4] 输出:6
解释: 子数组 [2,3] 有最大乘积 6。
思路
这题会发现,max[i]以i结尾的最大值不是由max[I-1]决定的,比如[-2,3,-5]这时候最大为30。
所以我们需要维护两个数组,分别表示以i结尾的乘积最大和最小值
答案
/**
* @param {number[]} nums
* @return {number}
*/
var maxProduct = function(nums) {
let ansMax=[nums[0]];
let ansMin=[nums[0]];
for(let i=1;i<nums.length;i++){
ansMax[i]=Math.max(ansMax[i-1]*nums[i],nums[i],ansMin[i-1]*nums[i]);
ansMin[i]=Math.min(ansMin[i-1]*nums[i],nums[i],ansMax[i-1]*nums[i]);
}
return Math.max(...ansMax);
};