JavaScript:leetcode_152. 乘积最大子数组(动态规划)

题目说明

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

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

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

解题思路一

  1. 该题与之前所写的560.和为K的子数组很相似,解法也都是一样的。
  2. 依旧是对前缀进行操作。不同的是,我们这次不需要保留所有的结果,只需要保留本次结果的最大值nowMax 和最小值nowMin 。取min主要是为了复数的情况。
  3. 我们依赖于上一次的状态,求出本次的最大最小值。然后传入下一次状态。
    1. nowMax = Math.max(res[0] * nums[i], res[1] * nums[i], nums[i]);
    2. nowMin = Math.min(res[0] * nums[i], res[1] * nums[i], nums[i]);
    3. res = [nowMax, nowMin ]
  4. 在此过程中我们可以求出最大值max

代码实现一

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
    if (!nums.length) {
        return 0;
    }
    let max = nums[0]
    let min = nums[0]
    let res = [nums[0], nums[0]];
    for (let i = 1 ; i < nums.length; i++) {
        let nowMax = Math.max(res[0] * nums[i], res[1] * nums[i], nums[i]);
        let nowMin = Math.min(res[0] * nums[i], res[1] * nums[i], nums[i]);
        max = Math.max(nowMax, max);
        // min = Math.min(nowMin, min);
        res = [nowMax, nowMin];
    }
    return max;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Eighteen Z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值