AlgoMaster Logo

Best Time to Buy and Sell Stock with Cooldown

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Recursive Brute Force

Intuition:

  • The idea here is to simulate each possible action (buy, sell, cooldown) at each day and keep track of the maximum profit.
  • For each day, we can either:
    1. Not make any transaction (cooldown).
    2. Buy a stock (if currently not holding one).
    3. Sell a stock (only if currently holding a stock).
  • We solve this using recursion by exploring each decision for each day and computing the maximum profit.

Code:

2. Memoization

Intuition:

  • The recursive solution computes the same subproblems multiple times, which increases time complexity.
  • We can store the results of subproblems in a 2D array to avoid recalculating them, turning our approach into a dynamic programming solution.

Code:

3. Dynamic Programming

Intuition:

  • Instead of recursion, we use dynamic programming arrays to keep track of the profits.
  • We define two arrays: sell[i] which is the maximum profit we can have up to day i (inclusive) and must sell on i, and buy[i] for transactions where max profit up to i and must buy on i.

Code:

4. Space Optimized Dynamic Programming

Intuition:

  • We can notice that to compute buy[i] and sell[i], we only need the values for i-1 and i-2.
  • Therefore, instead of maintaining arrays for buy and sell, we maintain only variables for the last two and current states.

Code: