Best Time to Buy and Sell Stock with Cooldown: A Comprehensive Guide
The "Best Time to Buy and Sell Stock with Cooldown" problem is a classic dynamic programming challenge in computer science. This problem explores the optimal strategy for maximizing profit when buying and selling stocks, with a cooldown period required between transactions.
Understanding the Problem
Imagine you're a stock trader with a unique rule: you can buy a stock, sell it for profit, and then must wait for a certain period (the cooldown) before buying again. This problem asks you to devise a plan that maximizes your profit over a given timeline of stock prices.
Approach: Dynamic Programming
Dynamic programming is a powerful technique for solving optimization problems. Here's how it works for the "Best Time to Buy and Sell Stock with Cooldown" problem:
-
Define Subproblems: We break the problem into smaller, overlapping subproblems.
dp[i][0]
: The maximum profit achievable after dayi
with no stock in hand.dp[i][1]
: The maximum profit achievable after dayi
with a stock in hand.dp[i][2]
: The maximum profit achievable after dayi
in cooldown.
-
Base Cases:
dp[0][0] = 0
: Starting with no stock, the profit is 0.dp[0][1] = -prices[0]
: Buying on day 0, the profit is the negative of the price.dp[0][2] = 0
: Initially in cooldown, the profit is 0.
-
Recursive Relation:
dp[i][0] = max(dp[i-1][0], dp[i-1][2])
: On dayi
, either we had no stock before (and still don't) or we were in cooldown and now have no stock.dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
: On dayi
, either we had a stock before or we bought a stock on dayi
.dp[i][2] = dp[i-1][1] + prices[i]
: On dayi
, we are in cooldown, meaning we sold the stock on the previous day.
-
Final Result: The maximum profit is stored in
dp[n-1][0]
(wheren
is the total number of days).
Example:
Let's say the stock prices are: [1, 2, 3, 0, 2]
.
Day | Price | dp[i][0] |
dp[i][1] |
dp[i][2] |
---|---|---|---|---|
0 | 1 | 0 | -1 | 0 |
1 | 2 | 0 | 1 | -1 |
2 | 3 | 1 | 3 | 1 |
3 | 0 | 3 | 3 | 6 |
4 | 2 | 6 | 5 | 8 |
The maximum profit achieved is 8.
Implementation (Python):
def maxProfit(prices):
n = len(prices)
if n <= 1:
return 0
dp = [[0] * 3 for _ in range(n)]
dp[0][0] = 0
dp[0][1] = -prices[0]
dp[0][2] = 0
for i in range(1, n):
dp[i][0] = max(dp[i-1][0], dp[i-1][2])
dp[i][1] = max(dp[i-1][1], dp[i-1][0] - prices[i])
dp[i][2] = dp[i-1][1] + prices[i]
return dp[n-1][0]
Time and Space Complexity:
- Time Complexity: O(n), where n is the number of days.
- Space Complexity: O(n) for the dynamic programming table.
Conclusion
The "Best Time to Buy and Sell Stock with Cooldown" problem is a great example of how dynamic programming can be used to solve complex optimization problems. By breaking the problem down into smaller, overlapping subproblems, we can efficiently calculate the optimal solution.