[LeetCode] Maximum Product Subarray

本文介绍了一种使用动态规划求解最大子数组乘积的方法,针对包含至少一个元素的数组,寻找具有最大乘积的连续子数组。通过维护最大值和最小值来处理负数的情况,并给出AC代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

  • 常规思路
class Solution {
public:
    int maxProduct(int A[], int n) {
        int product = INT_MIN;
        for (int i = 0; i < n; i++)
        {
            int sub = 1;
            for (int j = i; j < n; j++)
            {
                sub *= A[j];
                if (sub > product)
                {
                    product = sub;
                }
            }
        }

        return product;
    }
};

上述算法时间复杂度过高,LeetCode返回Time Limit Exceeded错误提示。

  • 动态规划思路
    由于数组中有负数存在,一个负数乘以一个负数可能得到一个极大的正数,因此需要维护两个局部变量max_localmin_local。转移方程式如下:
    temp = max_local;
    max_local[i] = max(max(max_local * A[i], min_local * A[i]), A[i]);
    min_local[i] = min(min(temp * A[i], min_local * A[i]), A[i]);
  • 实现代码
/*************************************************************
    *  @Author   : 楚兴
    *  @Date     : 2015/2/8 21:43
    *  @Status   : Accepted
    *  @Runtime  : 13 ms
*************************************************************/
class Solution {
public:
    int maxProduct(int A[], int n) {
        if (n == 0)
        {
            return 0;
        }

        int max_local = A[0];
        int min_local = A[0];
        int global = A[0];
        for (int i = 1; i < n; i++)
        {
            int temp = max_local;
            max_local = max(max(max_local * A[i], min_local * A[i]), A[i]);
            min_local = min(min(temp * A[i], min_local * A[i]), A[i]);
            global = max(global, max_local);
        }

        return global;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值