Leetcode - Maximum Product Subarray

本文介绍了一种求解最大连续子数组乘积的方法,并提供了两种解决方案:一种使用O(N)空间复杂度,另一种则优化为O(1)空间复杂度。通过递归更新最大值和最小值来处理负数的影响。

[题目] 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.

[分析] 注意到负负得正,所以求解过程中需要分别计算保留以当前数组元素A[i]结尾的连续子数组乘积的最大值和最小值

 

public class Solution {
    // O(N)空间 + O(N)时间
    public int maxProduct1(int[] A) {
        if (A == null || A.length == 0)
            return 0;
        int n = A.length;
        int[] max = new int[n];
        int[] min = new int[n];
        // 初始化条件
        max[0] = A[0];
        min[0] = A[0];
        int finalMax = A[0];
        for (int i = 1; i < n; i++) {
            // 递推式
            max[i] = Math.max(A[i], Math.max(max[i - 1] * A[i], min[i - 1] * A[i]));
            min[i] = Math.min(A[i], Math.min(max[i - 1] * A[i], min[i - 1] * A[i]));
            if (max[i] > finalMax)
                finalMax = max[i];
        }
        return finalMax;
    }
    
    // O(1)空间 + O(N)时间,仅需保留上一步的结果
    public int maxProduct(int[] A) {
        if (A == null || A.length == 0)
            return 0;
        int n = A.length;
        int[] max = new int[2];
        int[] min = new int[2];
        max[0] = A[0];
        min[0] = A[0];
        int finalMax = A[0];
        for (int i = 1; i < n; i++) {
            max[1] = Math.max(A[i], Math.max(max[0] * A[i], min[0] * A[i]));
            min[1] = Math.min(A[i], Math.min(max[0] * A[i], min[0] * A[i]));
            if (max[1] > finalMax)
                finalMax = max[1];
            max[0] = max[1];
            min[0] = min[1];
        }
        return finalMax;
    }
}

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值