152. 乘积最大子数组
mengjian-github opened this issue · comments
给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。
测试用例的答案是一个 32-位 整数。
子数组 是数组的连续子序列。
示例 1:
输入: nums = [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。
示例 2:
输入: nums = [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
这道题的难点在于,子问题有些复杂,假设以i为结尾的最大乘积做动态规划,有一个正负号的问题,所以得寻找最小值和最大值两个,取最大。
/**
* @param {number[]} nums
* @return {number}
*/
var maxProduct = function(nums) {
let preMin = nums[0];
let preMax = preMin;
let max = preMin;
for (let i = 1; i < nums.length; i++) {
const curMax = Math.max(preMax * nums[i], preMin * nums[i], nums[i]);
const curMin = Math.min(preMax * nums[i], preMin * nums[i], nums[i]);
max = Math.max(max, curMax);
preMax = curMax;
preMin = curMin;
}
return max;
};