Maximum Product Subarray - LeetCode

本文介绍了一种使用动态规划方法解决寻找具有最大乘积的连续子数组问题的算法。通过维护最大值和最小值来应对负数带来的乘积反转情况。

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

思路:DP。这里我们实际上不需要O(n)的空间,只需要用变量将遍历到的最大值记录下来就可以。

其中,因为求的是数的乘积,有可能原本两个都是负的值相乘后会成为最大的乘积。

因此,我们需要维护两个变量,MaxPre和MinPre。

MaxPre为最后一位是当前位置前一位的区间最大乘积。

MinPre为最后一位是当前位置前一位的区间最小乘积。

之后,将当前位置考虑在内的话,有:

MaxSoFar = max(max(MaxPre * nums[i], MinPre * nums[i]), nums[i]);

MinSoFar = min(min(MinPre * nums[i], MaxPre * nums[i]), nums[i]);

然后用MaxResFound记录下迭代过程中MaxSoFar的最大值,即为结果。

 1 class Solution {
 2 public:
 3     int maxProduct(vector<int>& nums) {
 4         int n = nums.size();
 5         if (n == 0) return 0;
 6         int MaxSoFar, MinSoFar, MaxResFound, MaxPre, MinPre;
 7         MaxPre = MinPre = MaxSoFar = MinSoFar = MaxResFound = nums[0];
 8         for (int i = 1; i < n; i++)
 9         {
10             MaxSoFar = max(max(MaxPre * nums[i], MinPre * nums[i]), nums[i]);
11             MinSoFar = min(min(MinPre * nums[i], MaxPre * nums[i]), nums[i]);
12             MaxResFound = max(MaxResFound, MaxSoFar);
13             MaxPre = MaxSoFar;
14             MinPre = MinSoFar;
15         }
16         return MaxResFound;
17     }
18 };

 

转载于:https://www.cnblogs.com/fenshen371/p/4935078.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值