#309

Best Time to Buy and Sell Stock with Cooldown

Medium
ArrayDynamic ProgrammingDynamic ProgrammingArray
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n)
Space
O(1)
O(1)
💡

Intuition

Time O(n)Space O(1)

Using dynamic programming, we can keep track of the maximum profit at each day while considering the cooldown period. This allows us to efficiently calculate the maximum profit without redundant calculations.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create three variables to track the maximum profit on the previous day with no stock, with stock, and the cooldown.
  2. 2Step 2: Iterate through the prices array and update these variables based on the current price and the previous states.
  3. 3Step 3: At the end, the maximum profit will be in the no stock variable.
solution.py9 lines
1def maxProfit(prices):
2    if not prices: return 0
3    sold, held, reset = 0, float('-inf'), 0
4    for price in prices:
5        prev_sold = sold
6        sold = held + price
7        held = max(held, reset - price)
8        reset = max(reset, prev_sold)
9    return sold

Complexity note: The time complexity is O(n) because we only pass through the prices array once. The space complexity is O(1) since we only use a fixed amount of extra space.

  • 1Understanding the cooldown period is crucial for making optimal decisions.
  • 2Dynamic programming allows us to build on previous results rather than recalculating.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.