[LeetCode] 152. 乘积最大子数组 ☆☆☆(动态规划)

乘积最大子数组

描述

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

示例 1:

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

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

解析

看起来和连续子数组的最大和类似,一个是和,一个是积。

其实有点不一样。如果当前元素为负数,那么当前元素的字数组最大值是前一个元素的最小值 * 当前元素。

所有,存储前一个元素的最小值min。当前元素为负数时,最大值为min * nums[i],最小值为max * nums[i]。

或者可以这么理解:当前元素为负数时,交换最大最小值即可。

代码


public int maxProduct(int[] nums) {
        if (null == nums || nums.length <= 0) {
            return Integer.MIN_VALUE;
        }
        int res = nums[0];
        int max = nums[0];
        int min = nums[0];
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] < 0) {//当前元素为负数,交换最大最小值
                int temp = max;
                max = min;
                min = temp;
            }
            max = Math.max(nums[i] * max, nums[i]);
            min = Math.min(nums[i] * min, nums[i]);
            res = Math.max(max, res);
        }
        return res;
}
原文地址:https://www.cnblogs.com/fanguangdexiaoyuer/p/12172923.html