算法列表

152.乘积最大子数组 中等

布莱克2026-02-25 08:50动态规划

问题:

给你一个整数数组 nums ,请你找出数组中乘积最大的非空连续 子数组(该子数组中至少包含一个数字),并返回该子数组所对应的乘积。

测试用例的答案是一个 32-位 整数。

请注意,一个只包含一个元素的数组的乘积是这个元素的值。

示例 1:

输入: nums = [2,3,-2,4]
输出: 6
解释: 子数组 [2,3] 有最大乘积 6。

示例 2:

输入: nums = [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

回答:

var maxProduct = function(nums) {
    if (nums.length == 1) return nums[0];
    //需要同时维护一个最大值和最小值,因为负负得正
    let max = nums[0];
    let min = nums[0];
    let res = nums[0]
    for (let i = 1; i < nums.length; i++) {
        let current = nums[i];
        let currentMax = Math.max(current, max * current, min * current);
        let currentMin = Math.min(current, max * current, min * current);
        max = currentMax;
        min = currentMin;
        res = Math.max(res, max)
    }
    return res;
};


assistant