最大乘积 动态规划

题目:

给定一个整数数组 nums ,找出一个序列中乘积最大的连续子序列(该序列至少包含一个数)。

示例 1:

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

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

1.直接循环

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
     let max = nums[0];
    if(nums.length==1){//为一个数的时候
        return max;
    }
    
    for(let i= 0;i<nums.length;i++){
        let start = nums[i];
        if(max<start){
            max = start;
        }
        for(let j=i+1;j<nums.length;j++){
            start = start*nums[j];
            if(max<start){
                max = start;
            }
        }
    }
    return parseInt(max);
};

2.动态规划

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
    let pre_min =nums[0];
    let pre_max =nums[0];
    let curren_max = nums[0];
    let res = curren_max;
    for(let i=1;i<nums.length;i++){
        if(nums[i]<0){//当当前元素是小于0的时候,将之前的最大最小值交换
            let temp = pre_max;
            pre_max =pre_min;
            pre_min = temp;
        }
        curren_max= Math.max(pre_max*nums[i],nums[i]);//当前的最大值就是之前最大值乘以当前的数据
        curren_min = Math.min(pre_min*nums[i],nums[i]);//当前最小值就是之值乘以当前的数据
        res = Math.max(curren_max,res);
        pre_min = curren_min;
        pre_max = curren_max;
    }
    return res;
};

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

原文地址:https://www.cnblogs.com/panjingshuang/p/11700651.html