【JS每日一算法】🟨147.乘积最大子数组(暴力破解、动态规划)

204 阅读1分钟

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

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

子数组 是数组的连续子序列。  

示例 1:

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

示例 2:

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

提示:

  • 1 <= nums.length <= 2 * 104
  • -10 <= nums[i] <= 10
  • nums 的任何前缀或后缀的乘积都 保证 是一个 32-位 整数

题解:

个人博客

更多JS版本题解点击链接关注该仓库👀

/**
 * @description: 暴力破解   TC:O(n^2)  SC:O(1)
 * @author: JunLiangWang
 * @param {*} nums  给定数组
 * @return {*}
 */
function bruteForce(nums){
    /**
     * 本方案使用暴力破解的方式,两次遍历数组元素
     * 比较其乘积获取最大乘积
     */
    let maxProduct=nums[0]
    for(let i=0;i<nums.length;i++){
        let product=1
        for(let j=i;j<nums.length;j++){
            product*=nums[j]
            maxProduct=Math.max(maxProduct,product)
        }
    }
    return maxProduct
}


/**
 * @description: 动态规划  TC:O(n)  SC:O(1)
 * @author: JunLiangWang
 * @param {*} nums 给定数组
 * @return {*}
 */
function dp(nums){
    let maxProduct=nums[0],
    negativeProduct=nums[0],
    positiveProduct=nums[0];
    for(let i=1;i<nums.length;i++){
        let temp1 = positiveProduct * nums[i],temp2 = negativeProduct * nums[i];
        positiveProduct=Math.max(temp1,temp2,nums[i]);
        negativeProduct=Math.min(temp1,temp2,nums[i]);
        maxProduct=Math.max(maxProduct,positiveProduct,negativeProduct)
    }
    return maxProduct;
}