乘积最大子序列

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

示例 1:

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

示例 2:

输入: [-2,0,-1]
输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。
暴力解法时间复杂度太高。将乘积保存在一个数组中,并且每次判断当前的数是正是负,正数就从 nmax 数组中取数字进行比较,负数就从 nmin 数组中取数字进行比较。
/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
    let nmax = [nums[0]];
    let nmin = [nums[0]];
    for(let i=1;i<nums.length;i++){
        if(nums[i]>0){
            nmax.push(Math.max(nmax[i-1]*nums[i],nums[i]));
            nmin.push(Math.min(nmin[i-1]*nums[i],nums[i]));
        }else{
            nmax.push(Math.max(nmin[i-1]*nums[i],nums[i]));
            nmin.push(Math.min(nmax[i-1]*nums[i],nums[i]));
        }
    }
    let result=nmax[0];
    for(let i=1;i<nmax.length;i++){
        if(nmax[i]>result){
            result = nmax[i];
        }
    }
    return result;
};

 

posted @ 2019-07-17 14:21  湛蓝的家  阅读(458)  评论(0编辑  收藏  举报