309. Best Time to Buy and Sell Stock with Cooldown

本文介绍了一种在股票交易中考虑冷却期的算法优化方法。通过动态规划技术,该算法能够在多次买入卖出的情况下,遵循冷却一天的规定,找到最大化利润的策略。

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

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:

prices = [1, 2, 3, 0, 2]
maxProfit = 3
transactions = [buy, sell, cooldown, buy, sell]

s思路:
1. 和 Leetcode 122. Best Time to Buy and Sell Stock II比,多了一天cooldown. 那代码如何建模或者模拟这个cooldown?
2. 难点是,cooldown是哪一天重要吗?需要尝试完所有的情况,然后找出最大值吗?这么看,这个角度很繁琐,可以主动换一个角度看问题吗?还是dp,回到数学递推公式来!
3. 忘了这个题应该是dp的题了,现在增加了一个cooldown,就不能用原来简化的dp来做了,参考了https://discuss.leetcode.com/topic/30421/share-my-thinking-process 
4. 假设buy[i]表示第i天之前包括第i天最后的操作是买入对应的最大profit;sell[i]表示第i天之前包括第i天最后的操作是卖出对应的最大profit。由于有一天cooldown,所以这两个数量的interplay就是如下:

buy[i]=max(sell[i-2]-price,buy[i-1]);//sell[i-2]表示i-2卖出,中间一天cooldown, 然后买入的价格为price. 还有一种可能是第i天不操作的收益最大,也就是等于buy[i-1].
sell[i]=max(buy[i-1]+price,sell[i-1]);//i-1天买入后的最大收益加上今天卖出后得到的收益,还有一种可能是第i天不卖出,收益最大,即:还等于sell[i-1].

5. 再次看出数学的牛!但是能用数学,前提是想明白了,而且认可这个数学,相信是数学关系,而不是模仿一下,这样下次还是搞不定!
6. 分析一下为什么数学可以表示cooldown呢?另外,分析一下此类问题,就是递推关系是几个状态之间相互转移的,有点像马尔科夫链一样,而什么问题可以模拟成状态转换呢?明天再写!

//方法1:dp,数学表示递推关系!
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        //
        int buy=INT_MIN;
        int sell[3]={0};
        for(int p:prices){
            int pre_buy=buy;
            buy=max(sell[0]-p,pre_buy);
            sell[2]=max(pre_buy+p,sell[1]);
            sell[0]=sell[1];
            sell[1]=sell[2];
        }
        return sell[2];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值