The original title link is here: https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
Topic:
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]
Exercises
Similar to the best time to Buy and Sell stock.
There are three states S0, S1, S2. S0 buy stock becomes s1, S1 sell stock becomes s2.
s0[I] =Maxs0[I1],s2[I1]);//StayAtS0,OrRestFromS2s1[I] =Maxs1[I1], s0[i-1]-prices[i]); //stay at S1, or buy from s0s2[i] = s1[i-1] + prices[i]; //only one way from s1
Time Complexity:o (n). Space:o (n).
AC Java:
1 Public classSolution {2 Public intMaxprofit (int[] prices) {3 if(Prices = =NULL|| Prices.length = = 0){4 return0;5 }6 intLen =prices.length;7 int[] S0 =New int[Len];8 int[] S1 =New int[Len];9 int[] s2 =New int[Len];Ten OneS0[0] = 0; AS1[0] =-prices[0]; -S2[0] = 0; - for(inti = 1; i<len; i++){ theS0[i] = Math.max (s0[i-1],s2[i-1]); -S1[i] = Math.max (s1[i-1], s0[i-1]-prices[i]); -S2[i] = s1[i-1] +Prices[i]; - } + returnMath.max (s0[len-1], s2[len-1]); - } +}
Reference:https://leetcode.com/discuss/72030/share-my-dp-solution-by-state-machine-thinking
Leetcode best time to Buy and Sell Stock with Cooldown