/** 309. best time to Buy and Sell Stock with Cooldown * 2016-7-4 by Mingyang *http://buttercola.blogspot.com/2016/01/leetcode-best-time-to-buy-and-sell.html * * * *. Define states * *to represent the decision at index I: *buy[i]: Max profit till index I. The series of transaction is ending with a buy. *SELL[I]: Max profit till index I. The series of transaction is ending with a sell. *to clarify: *till index I, the Buy/sell action must happen and must is the last action. * It may not be happen at index I. It may happen at I-1, I-2, ... 0. *in the end n-1, return sell[n-1]. Apparently we cannot finally end up with a buy. *in, we would rather take a rest at n-1. *for Special Case No transaction @ all, classify it as sell[i], so, the the end, we can still return sell[n-1]. * * *. Define recursion * *buy[i]: To make a decision whether to buy on I, we either take a rest, by just using the old D Ecision at I-1, *or sell At/before i-2, then buy at I, We cannot sell at I-1, then buy at I, because of Cooldow N. *sell[i]: To make a decision whetherTo sell in I, we either take a rest, by just using the old decision at I-1, *or buy At/before i-1, then sell at I . *so we get the following formula: *buy[i] = Math.max (Buy[i-1], sell[i-2]-prices[i]); *sell[i] = Math.max (Sell[i-1], buy[i-1] + prices[i]);*/ Public intMAXPROFIT5 (int[] prices) { if(Prices = =NULL|| Prices.length <= 1) { return0; } int[] Sell=New int[Prices.length]; int[] buy=New int[Prices.length]; buy[0] =-prices[0]; sell[0] = 0; buy[1]=math.max (buy[0],-prices[1]); sell[1]=math.max (sell[0],buy[0]+prices[1]); for(inti = 2; I <prices.length; i++) {Buy[i]=math.max (buy[i-1],sell[i-2]-Prices[i]); Sell[i]=math.max (sell[i-1],buy[i-1]+Prices[i]); } returnSell[prices.length-1]; }
309. Best time to Buy and Sell Stock with Cooldown