LeetCode题解:309. Best Time to Buy and Sell Stock with Cooldown

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 as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).
After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

Example:
Input: [1,2,3,0,2]
Output: 3 
Explanation: transactions = [buy, sell, cooldown, buy, sell]

解题思路

本题的操作逻辑如图:

购入 冷却 售出 next day next day next day next day(have sold) next day(have bought) next day 购入 冷却 售出

每天可操作的事项分为三种:购入新股票、售出持有股票、冷却期
假如选择购入新股票,那么下一天的操作可以是等待或者售出当前股票;
假如选择冷却期,那么下一天可以继续不操作或者购入股票(前面售出)或者出售股票(前面购入);
假如选择售出股票,那么下一天的操作只能是进入冷却期。
那么,它们的收益如下:
buy 代表购入新股票,那么收益为max(之前的余额,购入新股票的余额);
sell 代表售出股票,那么收益为之前的余额加售出所得的总和;
nothing 代表前一天不进行操作,那么当前的收益为max(继续等待,售出股票);

C++代码

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        if(prices.size() == 0 || prices.size() == 1){
            return 0;
        }
        int buy = -prices[0], sell = 0, nothing = 0;
        int preBuy, preSell, preNothing;
        for(int i = 1; i < prices.size(); i++) {
            preBuy = buy;
            preNothing = nothing;
            preSell = sell;
            buy = max(preBuy, preNothing-prices[i]);
            nothing = max(preNothing, preSell);
            sell = prices[i]+preBuy;
        }
        return max(sell, nothing);
    }
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

ZTao-z

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

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

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

打赏作者

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

抵扣说明:

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

余额充值