乘积最大子数组

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

function maxProduct(nums) {
    let maxsum = Math.max(...nums);
    if(nums.length == 1){
        return nums[0]
    }
    if(nums.length == 2 && nums.indexOf(0) > -1){
        return nums[0] == 0 ? nums[1] : nums[0]
    }
    for(let i = 0;i < nums.length-1;i++){
        let item = nums[i]
        let sum = Math.max(...nums);
        for(let j = i+1;j < nums.length;j++){
            let jItem = nums[j]
            item *= jItem
            if(item > sum){
                sum = item
            }
        }
        if(sum > maxsum){
            maxsum = sum
        }
    }
    return maxsum
}

Leecode测试用例全部通过,提交未通过(显示时间超时,我也不知道什么原因)

动态规划

/**
 * @param {number[]} nums
 * @return {number}
 */
const maxProduct = (nums = [2, 3, -2, 4]) => {
    let maxF = nums[0],
        minF = nums[0],
        ans = nums[0];
    let length = nums.length;
    for (let i = 1; i < length; ++i) {
        let mx = maxF,
            mn = minF;
        maxF = Math.max(mx * nums[i], Math.max(nums[i], mn * nums[i]));
        minF = Math.min(mn * nums[i], Math.min(nums[i], mx * nums[i]));
        ans = Math.max(maxF, ans);
    }
    return ans;
};

  

posted @ 2020-06-18 16:26  671_MrSix  阅读(123)  评论(0编辑  收藏  举报