LeetCode题库解答与分析——#152. 乘积最大子序列MaximumProductSubarray

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

例如, 给定序列 [2,3,-2,4]
其中乘积最大的子序列为 [2,3] 其乘积为 6


Find the contiguous subarray within an array (containing at least one number) which has the largest product.

For example, given the array [2,3,-2,4],
the contiguous subarray [2,3] has the largest product = 6.

他人思路:
设定当前最大值和最小值,对数组进行循环,对比( 当前数字 ×最大值 和(当前数字×最小值)分别与当前数值比大小,更新当前最大最小值,如果最大值大于总体最大值则取代之

代码(JavaScript):
/**
 * @param {number[]} nums
 * @return {number}
 */
var maxProduct = function(nums) {
    var max_now;
    var min_now;
    var max_last=nums[0];
    var min_last=nums[0];
    var max=nums[0];
    for(var i=1;i<nums.length;i++){
        max_now=Math.max(Math.max(max_last*nums[i],min_last*nums[i]),nums[i]);
        min_now=Math.min(Math.min(max_last*nums[i],min_last*nums[i]),nums[i]);
        max_last=max_now;
        min_last=min_now;
        max=Math.max(max_now,max);
    }
    return max;
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值