LeetCode 309: Best Time to Buy and Sell Stock with Cooldown Solution
Master LeetCode problem 309 (Best Time to Buy and Sell Stock with Cooldown), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
309. Best Time to Buy and Sell Stock with Cooldown
Problem Explanation
Explanation
To solve this problem, we can use dynamic programming with state machines. We can define three states: buy, sell, and cooldown. At each day, we can be in one of these states. We need to keep track of the maximum profit we can achieve at each state.
- sell[i]: Maximum profit on day
iif we sell on dayi. - buy[i]: Maximum profit on day
iif we buy on dayi. - cooldown[i]: Maximum profit on day
iif we are in cooldown on dayi.
We can update these states based on the following conditions:
- sell[i] = buy[i-1] + prices[i]
- buy[i] = max(cooldown[i-1] - prices[i], buy[i-1])
- cooldown[i] = max(sell[i-1], cooldown[i-1])
The final answer will be the maximum of sell[n-1] and cooldown[n-1], where n is the number of days.
Time complexity: O(n)
Space complexity: O(1)
Solution Code
class Solution {
public int maxProfit(int[] prices) {
if (prices == null || prices.length <= 1) {
return 0;
}
int sell = 0, buy = -prices[0], cooldown = 0;
for (int i = 1; i < prices.length; i++) {
int prevSell = sell;
sell = buy + prices[i];
buy = Math.max(cooldown - prices[i], buy);
cooldown = Math.max(prevSell, cooldown);
}
return Math.max(sell, cooldown);
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 309 (Best Time to Buy and Sell Stock with Cooldown)?
This page provides optimized solutions for LeetCode problem 309 (Best Time to Buy and Sell Stock with Cooldown) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 309 (Best Time to Buy and Sell Stock with Cooldown)?
The time complexity for LeetCode 309 (Best Time to Buy and Sell Stock with Cooldown) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 309 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 309 in Java, C++, or Python.