309. Best Time to Buy and Sell Stock with Cooldown

Say you have an array for which the ith element is the price of a given stock on day i.

Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:

  • You may not engage in multiple transactions at the same time (ie, you must sell the stock before you buy again).

  • After you sell your stock, you cannot buy stock on next day. (ie, cooldown 1 day)

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;
    }
}

Last updated