leetcode.Best Time to Buy and Sell Stock with Cooldown

本文详细解析了股票买卖问题中的动态规划算法,包括考虑交易费用、限制交易次数等多种情况。通过状态机的方式,定义了买入、卖出及休息三种状态,并给出具体的转移方程。

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

这里都用了状态机,需要注意的是状态机表示当前状态下的最大收益

a typical DP problem

key1 :   deduce the transition function .

(buy,sell,rest) represents before day i what is the max profit  when the  sequence end with (buy, sell ,rest)

buy[i] = max(rest[i-1]-price[i],buy[i-1])

sell[i] = max(buy[i-1] + price[i],sell[i-1])

rest[i] = max(buy[i-1],sell[i-1],rest[i-1])

key2: simplifize the function 

buy[i] = max(sell[i-2]-price[i],buy[i-1])

sell[i] = max(buy[i-1] + price[i],sell[i-1])

key3: initialize i = 0

buy[0] = max(INT_MIN, -price[0])

sell[0] = 0;

here is the code

int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if(len == 0) return 0;
        vector<int> buy(len);
        vector<int> sell(len);
        buy[0] = -prices[0];
        sell[0] = 0;
        for(int i = 1; i < len ; i++){
            if(i == 1){
                buy[1] = max(-prices[1],buy[0]);
            }else{
              buy[i] = max(sell[i-2]-prices[i],buy[i-1]);
            }
              sell[i] = max(buy[i-1]+prices[i],sell[i-1]);
        }
        return sell[len-1];
    }

714. Best Time to Buy and Sell Stock with Transaction Fee

一样的dp思想,需要注意的是一次买入再卖出才算一次transaction

int maxProfit(vector<int>& prices, int fee) {
        int len = prices.size();
        if(len == 0) return 0;
        vector<int> sell(len);
        vector<int> buy(len);
        buy[0] = -prices[0];
        sell[0] = 0;
        for(int i = 1; i < len ;i++){
            buy[i] = max(buy[i-1], sell[i-1]-prices[i]); //买入的时候不需要付费
            sell[i] = max(sell[i-1], buy[i-1]+prices[i] -fee);
        }
        return sell[len-1];
    }

123. Best Time to Buy and Sell Stock III

int maxProfit(vector<int>& prices, int fee) {

       if(prices.size() == 0) return 0;
       int s1 = -prices[0], s2 = INT_MIN, s3 = INT_MIN,s4 = INT_MIN;
       for(int i = 0; i < prices.size(); i++){
            s1 = max(s1, -prices[i]);
            s2 = max(s2, s1+prices[i]);
            s3 = max(s3, s2-prices[i]);
            s4 = max(s4, s3+prices[i]);
       }
       return max(0,s4);
    }

122. Best Time to Buy and Sell Stock II

int maxProfit(vector<int>& prices, int fee) {
        int len = prices.size();
        if(len == 0) return 0;
        vector<int> sell(len);
        vector<int> buy(len);
        buy[0] = -prices[0];
        sell[0] = 0;
        for(int i = 1; i < len ;i++){
            buy[i] = max(buy[i-1], sell[i-1]-prices[i]); 
            sell[i] = max(sell[i-1], buy[i-1]+prices[i]);
        }
        return sell[len-1];
    }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值