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]
 
int maxProfit(int* prices, int pricesSize) {
    //each time prices[i] has four cases: 
        //1: stock has 0 and do nothing -> has0_donothing 
            // -> prices[i - 1] : 1 or 4
        //2: stock has 0 and buy 1 -> has0_buy  
            // -> prices[i - 1] : 1
        //3: stock has 1 and do nothing -> has1_donothing 
            // -> prices[i - 1] : 2 or 3
        //4: stock has 1 and sell 1 -> has1_sell    
            // -> prices[i - 1] : 2 or 3
    // initialize four var
    int has0_donothing = 0;
    int has0_buy = -prices[0];
    int has1_donothing = -prices[0];
    int has1_sell = 0;
    
    //if size < 2 return 0
    if(pricesSize < 2)
        return 0;
    for(int i = 1; i < pricesSize; i++){
        has1_donothing = has1_donothing > has0_buy ? has1_donothing : has0_buy;
        has0_buy = -prices[i] + has0_donothing;
        has0_donothing = has0_donothing > has1_sell ? has0_donothing : has1_sell;
        has1_sell = prices[i] + has1_donothing;
    }
    
    // return mast be 1 or 4
    return has0_donothing > has1_sell ? has0_donothing : has1_sell;
}
  • 对于每个点,都有4种方式
    • 1、什么都没有, 什么都不干 :前一个必须是1或4
    • 2、什么都没有, 买入 : 前一个必须是1
    • 3、已经买了,什么都不干 : 前一个必须是2或3
    • 4、已经买了,卖出 : 前一个必须是2或3
  • 注意循环中,必须是这个顺序:因为变量之间必须使用的上一个循环的结果,不能受本次的
  • 一个点的收入,可以认为是卖出 - 买入;所以把买入与负号放一起
posted @ 2016-01-10 18:39  dylqt  阅读(160)  评论(0编辑  收藏  举报