KatInterview

309. Best Time to Buy and Sell Stock with Cooldown

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

The problem asks for the maximum profit from buying and selling a stock, with a unique constraint: after selling a stock, you must wait for one day (a "cooldown" period) before you can buy again. This dependency on past actions suggests that a dynamic programming approach is suitable. We can think of our state at any given day as one of three possibilities: holding a stock, having just sold a stock (and thus being in cooldown), or being free to buy a stock.

Solution

Best Time to Buy and Sell Stock with Cooldown in Python

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        # hold: max profit if we end the day with a stock
        # sold: max profit if we end the day by selling a stock
        # rest: max profit if we end the day with no stock and are not in cooldown
        
        # Initialize states
        # We can think of starting before day 0 with 0 profit and no stock.
        # It's impossible to have a stock before day 0, so hold is -infinity.
        hold = float('-inf')
        sold = 0
        rest = 0

        for price in prices:
            # The 'sold' value from the previous day is needed to calculate the new 'rest' state.
            # We store it before 'sold' is updated.
            prev_sold = sold
            
            # To be in 'sold' state today, we must have been in 'hold' state yesterday and sold at today's price.
            sold = hold + price

            # To be in 'hold' state today, we either held yesterday or rested yesterday and bought today.
            hold = max(hold, rest - price)

            # To be in 'rest' state today, we either rested yesterday or our cooldown from selling yesterday is over.
            rest = max(rest, prev_sold)

        # The final maximum profit cannot be in the 'hold' state.
        # It must be either 'sold' or 'rest'.
        return max(sold, rest)

Best Time to Buy and Sell Stock with Cooldown in Java

class Solution {
    public int maxProfit(int[] prices) {
        // hold: max profit if we end the day with a stock
        // sold: max profit if we end the day by selling a stock
        // rest: max profit if we end the day with no stock and are not in cooldown
        
        // Initialize states
        // We can think of starting before day 0 with 0 profit and no stock.
        // It's impossible to have a stock before day 0, so hold is -infinity.
        // Using Integer.MIN_VALUE, but need to be careful with additions. 
        // `hold + price` might overflow if price is large negative, but problem constraints say price >= 0.
        int hold = Integer.MIN_VALUE;
        int sold = 0;
        int rest = 0;

        for (int price : prices) {
            // The 'sold' value from the previous day is needed to calculate the new 'rest' state.
            // We store it before 'sold' is updated.
            int prevSold = sold;

            // To be in 'sold' state today, we must have been in 'hold' state yesterday and sold at today's price.
            // If hold is MIN_VALUE, this correctly results in a very small number, representing an impossible path.
            sold = hold + price;

            // To be in 'hold' state today, we either held yesterday or rested yesterday and bought today.
            hold = Math.max(hold, rest - price);

            // To be in 'rest' state today, we either rested yesterday or our cooldown from selling yesterday is over.
            rest = Math.max(rest, prevSold);
        }

        // The final maximum profit cannot be in the 'hold' state.
        // It must be either 'sold' or 'rest'.
        return Math.max(sold, rest);
    }
}

Best Time to Buy and Sell Stock with Cooldown in C++

class Solution {
public:
    int maxProfit(vector<int>& prices) {
        // hold: max profit if we end the day with a stock
        // sold: max profit if we end the day by selling a stock
        // rest: max profit if we end the day with no stock and are not in cooldown
        
        // Initialize states
        // We can think of starting before day 0 with 0 profit and no stock.
        // It's impossible to have a stock before day 0, so hold is -infinity.
        int hold = INT_MIN;
        int sold = 0;
        int rest = 0;

        for (int price : prices) {
            // The 'sold' value from the previous day is needed to calculate the new 'rest' state.
            // We store it before 'sold' is updated.
            int prev_sold = sold;

            // To be in 'sold' state today, we must have been in 'hold' state yesterday and sold at today's price.
            sold = hold + price;

            // To be in 'hold' state today, we either held yesterday or rested yesterday and bought today.
            hold = max(hold, rest - price);

            // To be in 'rest' state today, we either rested yesterday or our cooldown from selling yesterday is over.
            rest = max(rest, prev_sold);
        }

        // The final maximum profit cannot be in the 'hold' state.
        // It must be either 'sold' or 'rest'.
        return max(sold, rest);
    }
};

Best Time to Buy and Sell Stock with Cooldown in TypeScript

function maxProfit(prices: number[]): number {
    // hold: max profit if we end the day with a stock
    // sold: max profit if we end the day by selling a stock
    // rest: max profit if we end the day with no stock and are not in cooldown

    // Initialize states
    // We can think of starting before day 0 with 0 profit and no stock.
    // It's impossible to have a stock before day 0, so hold is -infinity.
    let hold = -Infinity;
    let sold = 0;
    let rest = 0;

    for (const price of prices) {
        // The 'sold' value from the previous day is needed to calculate the new 'rest' state.
        // We store it before 'sold' is updated.
        const prevSold = sold;

        // To be in 'sold' state today, we must have been in 'hold' state yesterday and sold at today's price.
        sold = hold + price;

        // To be in 'hold' state today, we either held yesterday or rested yesterday and bought today.
        hold = Math.max(hold, rest - price);

        // To be in 'rest' state today, we either rested yesterday or our cooldown from selling yesterday is over.
        rest = Math.max(rest, prevSold);
    }

    // The final maximum profit cannot be in the 'hold' state.
    // It must be either 'sold' or 'rest'.
    return Math.max(sold, rest);
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.