Best Time to Buy and Sell Stock with Cooldown

Updated on 13 May, 2025
Best Time to Buy and Sell Stock with Cooldown header image

Problem Statement

In the given problem, you are provided with an array called prices, where each element prices[i] represents the price of a stock on the ith day. Your objective is to determine the maximum profit possible from buying and selling stocks over the course of these days. You are permitted to conduct as many buy-and-sell transactions as you deem fit. However, there are specific rules that must be followed:

  • You cannot hold multiple stocks simultaneously; sell before buying another.
  • After a sale, there is a mandatory cooldown period of one day before you can purchase again.

This need to manage the timing of buys and sells, along with the cooldown constraint, adds a layer of complexity to the strategic planning of transactions.

Examples

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

Approach and Intuition

To approach this problem, understanding the behavior of stock prices and the impact of transaction timings is crucial. The primary goal is to buy low and sell high repetitively, harvesting profits from each transaction while obeying the cooldown period after each sale.

  1. Review the sequence of stock prices to identify potential profit opportunities—a rise in stock prices between days suggests a beneficial buy-sell cycle.
  2. Implement a dynamic programming based approach that maintains a record of profits in different states:
    • state_0: The maximum profit achieved so far without holding any stock and not being in a cooldown.
    • state_1: The maximum profit achieved so far holding one stock.
    • state_2: The maximum profit achieved having sold the stock and being in a cooldown.
  3. The state transitions for subsequent days are defined by:
    • Transition from state_0 to state_1 by buying stock, involving a profit decrement by the stock price of the current day.
    • Transition from state_1 to state_0 by selling stock, augmenting profit by the stock price of the current day.
    • Transition from state_1 to state_2 directly after a sale.
    • From state_2, you can move to state_0 post cooldown to either buy on the current day or continue without buying.
  4. Iterate over the array of prices while updating these state values according to the possible actions (buy, sell or cooldown).

The solution to this problem is highly reliant on correct state management with dynamic transitions based on historical data points and constraints, ensuring maximum profit extraction from the available series of prices.

Solutions

  • Java
java
class Solution {
  public int calculateMaxProfit(int[] stockPrices) {
    int[] maxProfits = new int[stockPrices.length + 2];

    for (int i = stockPrices.length - 1; i >= 0; i--) {
      int maxProfitCase1 = 0;
      for (int sellIndex = i + 1; sellIndex < stockPrices.length; sellIndex++) {
        int potentialProfit = (stockPrices[sellIndex] - stockPrices[i]) + maxProfits[sellIndex + 2];
        maxProfitCase1 = Math.max(potentialProfit, maxProfitCase1);
      }

      int maxProfitCase2 = maxProfits[i + 1];

      maxProfits[i] = Math.max(maxProfitCase1, maxProfitCase2);
    }
    return maxProfits[0];
  }
}

This Java solution addresses the problem of finding the maximum profit from stock prices allowing a cooldown period after selling a stock. The main function, calculateMaxProfit, accepts an array of stock prices.

The approach utilizes dynamic programming to build up a solution where each entry in maxProfits array represents the maximum profit that can be achieved starting from day i till the end. The array maxProfits is of length stockPrices.length + 2 to handle edge cases easily.

Here’s how the solution proceeds:

  • Work backwards from the last day using a loop. This ensures that every decision takes into account the maximum profit from future transactions.
  • For each day i, calculate the maximum profit in two cases:
    • maxProfitCase1: Calculate the profit for every possible sell day after buying on day i. This involves an inner loop over potential selling days (sellIndex). The profit for any selling day is the difference between the selling day's price and day i's price, added to the max profit from sellIndex + 2 (due to the cooldown).
    • maxProfitCase2: The profit if no transaction is made on day i, which is simply the profit from day i+1.
  • Compute the maximum of maxProfitCase1 and maxProfitCase2 to determine the best strategy for day i.
  • Finally, the function returns the value in maxProfits[0], which contains the maximum profit starting from the beginning of the stock list.

This solution ensures that all profitable transaction sequences are considered, integrating the cooldown constraint effectively.

Comments

No comments yet.