Taro Logo

Best Time to Buy and Sell Stock with Cooldown

#132 Most AskedMedium
0 views
Topics:
Dynamic Programming

You are given an array prices where prices[i] is the price of a given stock on the ith day.

Find the maximum profit you can achieve. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times) with the following restrictions:

  • After you sell your stock, you cannot buy stock on the next day (i.e., cooldown one day).

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again).

Example 1:

Input: prices = [1,2,3,0,2]
Output: 3
Explanation: transactions = [buy, sell, cooldown, buy, sell]

Example 2:

Input: prices = [1]
Output: 0

Constraints:

  • 1 <= prices.length <= 5000
  • 0 <= prices[i] <= 1000

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What should be returned if the input array is empty or has only a single element?
  2. Are the stock prices guaranteed to be non-negative integers, or can we expect negative values or floating-point numbers?
  3. Could the prices array be extremely large (e.g., $10^6$ elements), meaning $O(N)$ time complexity and $O(1)$ space complexity are expected?
  4. If no profit can be made (e.g., prices are strictly decreasing), should the function return $0$?
  5. Does the cooldown period apply only immediately after a sell (meaning we can buy on the day after the cooldown), or are there any restrictions on how many days we must wait?

Brute Force Solution

Approach

To find the absolute maximum profit from buying and selling a stock with a cooldown period, the brute force approach imagines trying every single combination of actions day by day. By exploring every possible timeline of buying, selling, or waiting, you can calculate the profit for each path and simply pick the highest one at the very end.

Here's how the algorithm would work step-by-step:

  1. Start at the very first day and imagine all the possible choices you could make on that day: you can either buy a stock or choose to do nothing.
  2. For every choice you make today, move forward to the next day and once again consider all possible actions based on what you did previously.
  3. Remember the rule that whenever you sell a stock, you must take a mandatory rest day on the day immediately following, meaning you cannot buy or sell during that cooldown period.
  4. Continue making these hypothetical choices day by day until you reach the final day of the entire timeline.
  5. Once you reach the end, calculate the total money made from that specific sequence of buying and selling.
  6. Go back and repeat this entire process for every other possible timeline of decisions you could have made from start to finish.
  7. Compare the total profits from every single timeline you explored and select the one that gave you the most money.

Code Implementation

def max_profit(prices):
    def explore_timelines(current_day, holding_status):
        if current_day >= len(prices):
            return 0
        
        # Branch into choices because we must evaluate every possible trading timeline
        do_nothing_profit = explore_timelines(current_day + 1, holding_status)
        
        if holding_status:
            # Sell the stock today and enforce cooldown by skipping the next day
            sell_profit = prices[current_day] + explore_timelines(current_day + 2, False)
            return max(do_nothing_profit, sell_profit)
        else:
            # Buy the stock today and transition into holding state
            buy_profit = -prices[current_day] + explore_timelines(current_day + 1, True)
            return max(do_nothing_profit, buy_profit)

    # Start exploring from the very first day with no stock currently held
    return explore_timelines(0, False)

Big(O) Analysis

Time Complexity
O(3ⁿ) – For each of the n days in the stock price array, the plain English approach explores up to 3 branching decisions representing buying, selling, or doing nothing, while respecting the cooldown rule. Across n days, this recursive exploration of every possible timeline generates a decision tree with a branching factor of roughly 3. This leads to approximately 3 to the power of n total operations, which simplifies exponentially to O(3ⁿ).
Space Complexity
O(N) – The brute force approach described relies on exploring every possible timeline of buying, selling, or waiting recursively day by day. As the algorithm steps through the entire timeline, the recursive calls add up to a maximum depth of N, where N is the number of days represented by the stock prices. Therefore, the auxiliary space is driven entirely by the recursion stack frames reaching a maximum depth of N. Simplifying this growth to Big O notation gives a linear space complexity of O(N).

Optimal Solution

Approach

Instead of checking every single combination of buying and selling, the optimal approach tracks the best possible money situation at each day based on what action you just took. By keeping track of a few distinct financial states as you move forward in time, you can make the most profitable decisions without doing redundant work.

Here's how the algorithm would work step-by-step:

  1. Imagine you wake up each morning with three possible financial mindsets: you either currently hold a share, you just sold a share and must rest, or you are completely free to buy a share.
  2. On the very first day, your choices are very limited since you have to start fresh, meaning you either buy your very first share or wait patiently.
  3. As you move day by day through the timeline, look at how each action affects your wealth compared to the previous day.
  4. If you decide to hold a share today, it means you either kept the share you already had from yesterday or you freshly bought one today after being free for a while.
  5. If you decide to sell a share today, it means you definitely had to be holding one yesterday and you are now cashing in your profit.
  6. If you decide to rest today, it means you either were already resting or you just finished a mandatory cooling-off period right after a recent sale.
  7. After walking through the entire timeline day by day, look at the final outcomes where you are not holding any shares, and choose the one with the maximum profit.

Code Implementation

def max_profit(stock_prices):
    if not stock_prices:
        return 0

    holding_share = -stock_prices[0]
    sold_share = 0
    free_to_buy = 0

    # Track maximum wealth across distinct financial states as time moves forward
    for current_price in stock_prices[1:]:
        previous_holding = holding_share
        holding_share = max(holding_share, free_to_buy - current_price)

        # Cashing in profit requires holding a share yesterday
        sold_share = previous_holding + current_price

        # Mandatory cooling off or resting maintains the best free state
        free_to_buy = max(free_to_buy, sold_share)

    # Final outcomes without holding shares yield the maximum profit
    return max(sold_share, free_to_buy)

Big(O) Analysis

Time Complexity
O(n) – The algorithm iterates through the price array of size n exactly once from left to right. During each day, it performs a constant number of arithmetic operations and state updates to calculate the maximum profit for holding, selling, and resting. Since the workload per day is O(1), the total operations scale linearly as 1 * n steps. This simplifies directly to a final time complexity of O(n).
Space Complexity
O(1) – To track the best possible money situation as described in the steps, we only need a few scalar variables representing our financial states for the current and previous days rather than keeping history for all days. As the input timeline of length N moves forward, these few persistent variables overwrite their values in place instead of creating an auxiliary array or data structure of size N. Therefore, the extra memory used remains constant regardless of how many days are in the timeline, resulting in an optimal auxiliary space complexity of O(1).

Edge Cases

Empty or null price array
How to Handle:
Return zero profit immediately since no transactions can be made.
Array with a single element
How to Handle:
Return zero profit because buying and selling requires at least two distinct days.
Array with exactly two elements where the second is greater than the first
How to Handle:
Buy on day zero and sell on day one to capture the single profitable transaction without violating cooldown constraints.
Strictly monotonically decreasing prices
How to Handle:
Maintain zero profit as no profitable selling opportunity ever arises.
Strictly monotonically increasing prices
How to Handle:
Buy, sell, cooldown, and repeat whenever prices rise, capturing multiple intermediate profits instead of just the endpoints.
Large input size up to the maximum constraints
How to Handle:
Use an O(n) dynamic programming approach with constant space to efficiently handle large arrays without exceeding time or memory limits.
Prices with all identical values
How to Handle:
Yield zero profit since no price differential exists between days.
Inputs with extreme boundary values near the integer limits
How to Handle:
Use standard 32-bit or 64-bit integers where cumulative profit calculations will not overflow given standard financial constraints.
0/257 completed