152. Maximum Product Subarray(js)

Posted xingguozhiming

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了152. Maximum Product Subarray(js)相关的知识,希望对你有一定的参考价值。

152. Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:

Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.

Example 2:

Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

题意:给定一个数字数组(包含正数,负数和零),求连续子数组项的乘积的最大值
代码如下:
/**
 * @param number[] nums
 * @return number
 */
var maxProduct = function(nums) 
    let mx=nums[0];
    let mn=nums[0];
    let res=nums[0];
    
    for(let i=1;i<nums.length;i++)
//         max:数组前i+1项的最大乘积
//         min:数组前i+1项的最小乘积
//         dp思想,不断比较之前数组项的最小值*当前项,当前项,之前数组项的最大值*当前项,并不断更新最大值
        let max=mx,min=mn;
        mx=Math.max(Math.max(min*nums[i],nums[i]),max*nums[i]);
        mn=Math.min(Math.min(max*nums[i],nums[i]),min*nums[i]);
        res=Math.max(res,mx);
    
    return res;
;

 

以上是关于152. Maximum Product Subarray(js)的主要内容,如果未能解决你的问题,请参考以下文章

152. Maximum Product Subarray(js)

152. Maximum Product Subarray

leetcode 152. Maximum Product Subarray

刷题152. Maximum Product Subarray

LeetCode 152. Maximum Product Subarray

152. Maximum Product Subarray