买股票最佳时机 之 Leetcode的Best Time to Buy and Sell Stock III 问题解答

本文介绍了一种高效解决LeetCode上Best Time to Buy and Sell Stock III问题的方法,通过动态规划计算两次交易的最大利润,附带AC C++代码。

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

leetcode有一系列买股票最佳时机问题,其中最难的当属第三道Best Time to Buy and Sell Stock III ,问题描述为:

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete at most two transactions.

Note:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

根据题干要求,最多只能有两次交易。我们很容易想到问题 Best Time to Buy and Sell Stock I,基于问题I,针对每一个交易日i,可以对其左边和右边分别DP求解问题 I,但是显然这样的时间复杂度为O(n^2)。

从另一个角度来思考这个问题,以每一个交易日i为单位,我们分别计算在这一天卖出和买进所能获得的最大收益(当然当天可以只卖出或者只买进),最后比较求出最大的一个收益即可。

下面是AC的C++代码,击败了99.47%的C++答案,说明该答案的效率很高,大家可以借鉴下。

leftmin表示第0-i天之间的最小股价;

rightmax表示第i-n-1天的最大股价;

left[i]表示第i天以及之前卖出所能获得的最大收益,递推表达式为left[i]=max(left[i-1],p[i]-leftmin);

right[i]表示第i天以及之后买入所能获得的最大收益,递推表达式为right[i]=max(right[i+1],rightmax-p[i]);

最后求全局最优解,得到最多交易两次所能获得的最大收益;

class Solution 
{
public:
    int maxProfit(vector<int>& p)
    {
        int m=p.size();
        if(m<2) return 0;
        int leftmin=p[0];
        int rightmax=p[m-1];
        vector<int> left(m,0);
        vector<int> right(m,0);
        for(int i=1;i<m;i++)
        {
            leftmin=min(leftmin,p[i]);
            left[i]=max(left[i-1],p[i]-leftmin);
        }
        for(int j=m-2;j>=0;j--)
        {
            rightmax=max(rightmax,p[j]);
            right[j]=max(right[j+1],rightmax-p[j]);
        }
        int sum=0;
        for(int i=0;i<m;i++)
        {
            if(left[i]+right[i]>sum) sum=left[i]+right[i];
        }
        return sum;
    }
};

希望以上解释对大家有所帮助!
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值