LeetCode解析---152. 乘积最大子数组

题目

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

示例 1:

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

示例 2:

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

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/maximum-product-subarray
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解析

我们先考虑都是正数的情况。dp_max[i] 的含义为最大值,dp_max[i] = Math.max(nums[i-1],dp_max[i-1]*nums[i-1]),即 dp_max[i] 这个值只会在这两者产生,要么 乘上之前的会更大,要么 舍弃前面的。
接下来考虑负数的情况,所以我们有必要维护一个 dp_min,思路是一模一样的,当遍历的元素为负数时,我们只需要把 dp_max[i-1],dp_min[i-1]交换即可。

public int maxProduct(int[] nums) {
    int n = nums.length;
    if (n == 0) {
        return 0;
    }
    int dpMax = nums[0];
    int dpMin = nums[0];
    int max = nums[0];
    for (int i = 1; i < n; i++) {
        //更新 dpMin 的时候需要 dpMax 之前的信息,所以先保存起来
        int preMax = dpMax;
        dpMax = Math.max(dpMin * nums[i], Math.max(dpMax * nums[i], nums[i]));
        dpMin = Math.min(dpMin * nums[i], Math.min(preMax * nums[i], nums[i]));
        max = Math.max(max, dpMax);
    }
    return max;
}
原创文章 15 获赞 2 访问量 359

猜你喜欢

转载自blog.csdn.net/weixin_46747130/article/details/105913076