码迷,mamicode.com
首页 > Web开发 > 详细

152. Maximum Product Subarray(js)

时间:2019-07-22 20:16:10      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:class   function   least   with   pre   包含   output   最小值   number   

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)

标签:class   function   least   with   pre   包含   output   最小值   number   

原文地址:https://www.cnblogs.com/xingguozhiming/p/11227947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!