Dynamic Programming (stock exchange) --- require cooling-off period of stock trading

Required cooling-off period of stock trading

309. Best Time to Buy and Sell Stock with Cooldown(Medium)

Subject description:

  Principles of stock trading is to buy and then sell before buying must be at least one day off, finally seeking the maximum benefit that can be obtained.

Analysis of ideas:

Dynamic programming ideas:

  sell [i], represents the maximum benefits under the hands of the stock is not the end of the day after the case has been obtained.

  hold [i], represents the maximum benefits under the hands of a stock of the situation after the end of the day, it has been obtained.

State transition equation is this:

  sell [i], represents not the hands of stock returns, this possibility is sold today, or nothing dry. Today had nothing to do that is to sell [i] = sell [i-1], today sell, then sell [i] is to have income plus stock today sold stock price the day before. sell [i] = hold [i-1] + price [i]

  因此:sell[i]=max(sell[i-1],hold[i-1]+price[i])

  hold [i], said today the hands of profit shares, this possibility is to buy the stock today or nothing dry. Today had nothing to do that is to hold [i] = hold [i-1], buy the stock today, then hold [i] = sell [i-2] -price [i]

  因此:hold[i]=max(hold[i-1],sell[i-2]-price[i])

Code:

public int maxProfit(int []prices){
    if(prices==null||prices.length==0)
        return 0;
    int []sell=new int[prices.length];
    int []hold=new int[prices.length];
    sell[0]=0;
    hold[0]=-prices[0];
    for(int i=1;i<prices.length;i++){
        sell[i]=Math.max(sell[i-1],hold[i-1]+prices[i]);
        hold[i]=Math.max((i>=2?sell[i-2]:0)-prices[i],hold[i-1]);
    }
    return sell[prices.length-1];
}

Guess you like

Origin www.cnblogs.com/yjxyy/p/11121220.html