Say you has an array for which the i-th element is the price of a given-stock on day I.
Design an algorithm to find the maximum profit. Many transactions as (ie, buy one and sell one share of the stock multiple times) with the FO Llowing Restrictions:
- Engage in multiple transactions on the same time (ie, you must sell the stock before you buy again).
- After you sell your the stock, you cannot buy the stock on next day. (ie, cooldown 1 day)
Example:
Prices = [1, 2, 3, 0, 2]maxprofit = 3transactions = [Buy, Sell, cooldown, buy, sell]
intMaxprofit (int* Prices,intpricessize) { //Each time Prices[i] have four cases://1:stock has 0 and does 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 does 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 intHas0_donothing =0; intHas0_buy =-prices[0]; inthas1_donothing =-prices[0]; intHas1_sell =0; //If size < 2 return 0 if(Pricessize <2) return 0; for(inti =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 returnhas0_donothing > Has1_sell?Has0_donothing:has1_sell;}
- For each point, there are 4 different ways
- 1, nothing, nothing to do: the previous one must be 1 or 4
- 2, nothing, buy: The previous one must be 1
- 3, already bought, do nothing: the previous one must be 2 or 3
- 4, already bought, sold: the previous one must be 2 or 3
- Note that the loop must be in this order: The result of the previous loop that must be used between the variables cannot be affected by this
- A point of income that can be thought of as a sell-buy; so put the buy with the minus sign together
best time to Buy and Sell Stock with Cooldown