Best Time to Buy And Sell Stock With Cooldown

Best Time to Buy And Sell Stack With Cooldown

  • This problem is a variation of the classic “Buy and Sell Stock” challenge, incorporating a cooldown period after selling.
  • The goal is to maximize profit by strategically planning when to buy, sell, and stay idle.
N Queen problem for Chess

Best Time to Buy And Sell Stock With Cooldown Problem Description:

You are given an array prices where prices[i] represents the price of a stock on day ii. You may complete as many transactions as you’d like (buy one stock and sell one stock), but with the following restrictions:

  1. After selling a stock, you must wait for one day before buying again (cooldown period).
  2. You may only hold one stock at any given time.

Return the maximum profit achievable.

Example 1:

Example of N Queen problem

Explanation: Buy on day 0 (price = 1) and sell on day 1 (price = 3), profit = 3-1 = 2. Then buy on day 3 (price = 0) and sell on day 4 (price = 4), profit = 4-0 = 4. Total profit is 2 + 4 = 6.

Constraints:

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

Best Time to Buy And Sell Stock With Cooldown Solution

Recommendation for Time and Space Complexity – The solution should aim for O(n!) time and O(n²) space, where n is the size of the chessboard.

Hints for solving problems

There are mainly 4 approach to solve this problem-

  1. Recursion
  2. Dynamic Programming (Top-Down)
  3. Dynamic Programming (Bottom-up)
  4. Dynamic Programming (Space Optimized)

1. Recursion

  • Time complexity: O(n^2)
  • Space complexity: O(n)

2.Dynamic Programming (Top-Down)

    • Time complexityO(n)
    • Space complexityO(n)

3. Dynamic Programming (Bottom-Up)

  • Time complexity: O(n)
  • Space complexity: O(n)

4. Dynamic Programming (Space Optimized)

  • Time complexity: O(n)
  • Space complexity: O(1)

More Articles