LeetCode-152:Maximum Product Subarray (乘积最大连续子数组) -- medium

Question

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.

问题解析:

给定数组,给出最大乘积的连续子数组。

Answer

Solution 1:

DP。

  • 子数组问题很适合使用动态规划来求解,与和最大的连续子数组的思想是相同的。
  • 动态规划问题最核心的思想是找到其状态转移方程。首先说明“和最大的连续子数组”:我们定义, Fi 表示以 i 结尾的和最大的连续子数组,求F0,..,Fn1的最大值。所以这里我们最主要的是处理数组的局部当前最大连续乘积,和全局最大连续乘积的关系。
  • 转换为式子有:
    Fi=Max(Fi1+Ai,Ai);global=Max(Fi,global);
  • 与最大和连续子数组相似,最大乘积连续子数组具有相同的思想,只是需要考虑负数的情况,因为两个负数相乘时,最后得到正值。所以一方面我们在保存乘积最大的值的同时,也要保存最小值(乘负数就是最小),然后比较最小值乘当前值、最大值乘当前值、当前值三者之间的最大和最小值,最大值和全局值比较。
  • 转换为式子有:
    maxFi=Max(maxFi1Ai,Ai,minFi1Ai);minFi=Min(minFi1Ai,Ai,maxFi1Ai);global=Max(maxFi,global);
class Solution {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];

        int[] maxhere = new int[nums.length];
        int[] minhere = new int[nums.length];
        maxhere[0] = nums[0];
        minhere[0] = nums[0];
        int res = nums[0];

        for (int i = 1; i < nums.length; i++){
            maxhere[i] = Math.max(Math.max(maxhere[i-1]*nums[i], nums[i]), minhere[i-1]*nums[i]);
            minhere[i] = Math.min(Math.min(minhere[i-1]*nums[i], nums[i]), maxhere[i-1]*nums[i]);
            res = Math.max(res, maxhere[i]);
        }

        return res;
    }
}
  • 时间复杂度:O(n),空间复杂度:O(n)
Solution 2:

对Solution1的DP优化。

  • 通过观察状态转移函数,我们可以看出,每次计算只是用到前一个maxhereminhere,所以这里可以对程序进行改进,每次对前一个maxhereminhere做记录,这样就节省了空间的存储。
  • 因为在我们的程序中,先计算maxhere,后计算minhere,所以只有在计算minhere时,当前的maxhere[i]会覆盖之前的maxhere[i-1],所以我们在每次计算前,将前一个minhere保存下来,以便后面计算使用。
class Solution {
    public int maxProduct(int[] nums) {
        if (nums == null || nums.length == 0) return 0;
        if (nums.length == 1) return nums[0];

        int maxhere = nums[0];
        int minhere = nums[0];
        int res = nums[0];

        for (int i = 1; i < nums.length; i++){
            int maxpre = maxhere;
            maxhere = Math.max(Math.max(maxpre*nums[i], nums[i]), minhere*nums[i]);
            minhere = Math.min(Math.min(minhere*nums[i], nums[i]), maxpre*nums[i]);
            res = Math.max(res, maxhere);
        }

        return res;
    }
}
  • 时间复杂度:O(n),空间复杂度:O(1)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值