[Leetcode] Maximum Product Subarray

本文探讨了如何找到数组中具有最大连续乘积的子数组,并提供了两种解决方案:一种是通过逐个元素计算乘积的方法,另一种是使用动态规划的方法。详细解释了算法的实现过程和性能优化。

摘要生成于 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.


Solution:

Suppose there are no 0 in the array, then the answer of an array [0, ... ,n] must comes from [0, ..., i] or [i, ..., n].

Proof: 

1. If there are no negative number or there are even negative number, the answer is [0,n];

2. If there are odd negative number, say m, then we can choose m-1 negative number. That is, the subarray always contains one end of the array.

Consider there might be 0 in the array, we just need to break the array and run the algorithm above;


Code:

int maxProduct(vector<int>& nums) {
        int max = nums[0];
        int product;
        int begin = 0;
        int i;
        while( begin < nums.size() )
        {
            if( nums[begin] == 0 )
            {
                begin++;
                continue;
            }
            product = nums[begin];
            if( product > max ) max = product;
            for( i = begin+1; i < nums.size() && nums[i] != 0; i++ )
            {
                product *= nums[i];
                if( product > max ) max = product;
            }
            if( i < nums.size() && max < 0 ) max = 0;
            while( begin < i-1 )
            {
                product /= nums[begin];
                if( product > max ) max = product;
                begin++;
            }
            begin = i+1;
        }
        return max;
    }
runtime: 4ms


Solution 2:

DP, code:

int maxProduct(vector<int>& nums) {
        if( nums.size() == 0 ) return 0;
        int mmax;
        int maxLocal, minLocal;
        maxLocal = nums[0];
        minLocal = nums[0];
        mmax = nums[0];
        for( int i = 1; i < nums.size(); i++ )
        {
            int preMaxLocal = maxLocal;
            maxLocal = max( minLocal*nums[i], max( maxLocal*nums[i], nums[i] ) );
            minLocal = min( preMaxLocal*nums[i], min( minLocal*nums[i], nums[i] ) );
            mmax = max( mmax, maxLocal );
        }
        return mmax;
    }

runtime: 8ms

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值