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:

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


简单的说就是买卖停买卖停,

分析:

在第i天中,只有会两种状态(有无股票)和3种操作(买卖停),由于买卖有限制,所以只有四种可能。

1、有,卖了; 2、有,啥都不干; 3、无,买;4、无,啥都不干。

每一天有四种可能,而这四种可能又来至昨天,那么得到:

昨天做了2、3今天才能做1,也就是1状态的profit取决于昨天的2、3。

同样2、3=>2;4=>3;1、4=>4。

每天都更新这四个状态的值就可以得到最后的结果,比较一下大小即可,这里只比较1、4即可,因为做后一天进行2、3肯定不是可取的。

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int len = prices.size();
        if(len < 2){
            return 0;
        }
        int one_sell = 0;
        int one_nothing = -prices[0];
        int zero_buy = -prices[0];
        int zero_nothing = 0;
        for(int i=1; i<len; i++){
            one_nothing = one_nothing > zero_buy ? one_nothing : zero_buy;
            zero_buy = zero_nothing - prices[i];
            zero_nothing = zero_nothing > one_sell ? zero_nothing : one_sell;
            one_sell = one_nothing + prices[i]; 
        }
        return one_sell > zero_nothing ? one_sell : zero_nothing;
    }
};

这题使用dp思想并不太合适,因为当前问题的子问题只涉及到前一天的问题,严谨递推即可;也就是我们只得到前一天的状态即可对当前问题做出决定,并且前一天的状态只会在当前使用一次就无需再使用,而且4个状态之间有转变的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值