Leetcode 152. Maximum Product Subarray javascript解决方案

题意数组

给一串整数,可能为正数、负数、0,求连续一串能获得的最大积。

思路bash

根据0来断开一个个子串分别处理。 子串处理方式:子串所有相乘,由于没有小数,若是结果为正数,则返回乘积,负数就从左数和从右数,数到负数结束,看那边获得的数值更小,也就是负数更负,把乘积除以这个左右数中更小的值,就是这个子串的最大乘积。
选出子串中的最大返回值。
几个特殊状况:
数组长度为1,返回第一个
ui

代码:spa

/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
    /**
     * @param {number[]} non 0 number list
     * @return {number} max product
     */
    function handleNonZeroList(list){
        if(list.length < 2){
            return list[0];
        }
        let productTotal = 1;
        list.forEach(obj => {
            productTotal *= obj;
        });
        if(productTotal > 0){
            return productTotal;
        }
        let leftProduct = 1, leftMinus = -1;
        for(let i = 0;i < list.length; ++i){
            if(list[i] < 0){
                leftMinus = list[i];
                break;
            }
            leftProduct *= list[i];
        }
        leftProduct *= leftMinus;
        let rightProduct = 1, rightMinus = -1;
        for(let i = list.length - 1;i >= 0; --i){
            if(list[i] < 0){
                rightMinus = list[i];
                break;
            }
            rightProduct *= list[i];
        }
        rightProduct *= rightMinus;
        return productTotal /= (leftProduct > rightProduct ? leftProduct : rightProduct);
    }
    if(nums.length < 2){
        return nums[0];
    }
    let arrays = [], tmpList = [], hasZero = false;
    for(let i = 0;i < nums.length; ++i){
        if(nums[i] === 0){
            hasZero = true;
            if(tmpList.length > 0){
                arrays.push(tmpList);
                tmpList = [];
            }
        }
        else{
            tmpList.push(nums[i]);
        }
    }
    if(tmpList.length > 0){
        arrays.push(tmpList);
        tmpList = [];
    }
    let max = 0;
    for(let i = 0; i < arrays.length; ++i){
        let tmp = handleNonZeroList(arrays[i]);
        if(tmp > max){
            max = tmp;
        }
    }
    if(max < 0 && hasZero){
        return 0;
    }
    return max;
};

复制代码
相关文章
相关标签/搜索