LeetCode 题解:152. Maximum Product Subarray

Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Example 1:
Input: [2,3,-2,4]
Output: 6
Explanation: [2,3] has the largest product 6.
Example 2:
Input: [-2,0,-1]
Output: 0
Explanation: The result cannot be 2, because [-2,-1] is not a subarray.

解题思路

这道题和之前所做的求各元素相加和最大的数组子序列的解法相近,都是使用了动态规划算法。但不同的是,乘法子序列的最大结果会在以下两种情况中产生:前面累乘得到的最大值的子序列与当前元素(正数)相乘、前面累乘得到的最小值与当前元素(负数)相乘。因此我们需要维护三个值,一个记录前面子序列累乘的得到的最大值,一个记录前面子序列累乘的得到的最小值,还有一个全局最大值。

各个数值的确定方法:

局部最小值:最大值 * 当前元素最小值 * 当前元素当前元素 三者中的最小值
局部最大值:最大值 * 当前元素最小值 * 当前元素当前元素 三者中的最大值
全局最大值:局部最大值中的最大值

C++代码

class Solution {
public:
    int maxProduct(vector<int>& nums) {
        int min_local, max_local, Max;
        
        if(nums.size() == 1)
            return nums[0];
        
        min_local = nums[0];
        max_local = nums[0];
        Max = nums[0];
        
        for(int i = 1; i < nums.size(); i++) {
            int a = max_local*nums[i],
                b = min_local*nums[i];
            max_local = max(max(a, b), nums[i]);
            min_local = min(min(a, b), nums[i]);
            Max = max(Max, max_local);
        }
        return Max;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ZTao-z

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值