309. Best Time to Buy and Sell Stock with Cooldown
class Solution {
public int maxProfit(int[] prices) {
// set hold[i] is the max profit if day i is to buy or hold stock (hold stock)
// set sold[i] is the max profit if day i is to sell or day i-n (i-n>0) is sell and then take rest to day i (does not hold stock)
// if i is the day of hold: if day i is to buy a stock, then i-2 must be solid; if day i is to hold and rest, then day i-1 must be hold
// hold[i] = Math.max(sold[i-2]-prices[i], hold[i-1])
// if i is sold: if day i sell the stock: day i-1 must be hold state, if day i do nothing, i-1 must be sold
// sold[i] = Math.max(hold[i-1]+prices[i], sold[i-1])
// the result = sold[n-1];
// basecase sold[0]=0; hold[0] =0-prices[0];
//optimize memory to O(1)
if (prices.length<1) return 0;
int preHold = -prices[0];
int preSold = 0;
int prePreSold = 0;
for (int i=1; i<prices.length; i++){
int temp = preSold;
preSold =Math.max(preHold+prices[i], preSold);
preHold = Math.max(prePreSold-prices[i],preHold);
prePreSold = temp;
}
return preSold;
}
}Previous121. Best Time to Buy and Sell StockNext714. Best Time to Buy and Sell Stock with Transaction Fee
Last updated