leetcode152-乘积最大子数组

原题

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

示例 1:

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

示例 2:

输入: [-2,0,-1] 输出: 0
解释: 结果不能为 2, 因为 [-2,-1] 不是子数组。

解法

思想

动态规划?正负之间的转换其实就是最大值和最小值之间的转换。

代码

class Solution {
    public int maxProduct(int[] nums) {
        int prevMin = nums[0], prevMax = nums[0], res = nums[0];
        int temp1 = 0, temp2 = 0;
        for (int i = 1; i < nums.length; i++) {
            temp1 = nums[i] * prevMax;
            temp2 = nums[i] * prevMin;
            prevMax = Math.max(Math.max(temp1, temp2), nums[i]);
            prevMin = Math.min(Math.min(temp1, temp2), nums[i]);
            res = Math.max(res, prevMax);
        }
        return res;
    }
}

原创文章,作者:彭晨涛,如若转载,请注明出处:https://www.codetool.top/article/leetcode152-%e4%b9%98%e7%a7%af%e6%9c%80%e5%a4%a7%e5%ad%90%e6%95%b0%e7%bb%84/

(0)
彭晨涛彭晨涛管理者
上一篇 2020年5月17日
下一篇 2020年5月18日

相关推荐

发表回复

登录后才能评论