309. Best Time to Buy and Sell Stock with Cooldown

来源:互联网 发布:php pdo是什么 编辑:程序博客网 时间:2024/05/21 00:45

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 = 3transactions = [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个状态之间有转变的。


阅读全文
0 0