Leetcode 309: Best Time to Buy and Sell Stock with Cooldown

grid47
grid47
Exploring patterns and algorithms
Oct 7, 2024 7 min read

A graph of stock prices where the optimal buying and selling points are gently illuminated, with cooldown periods clearly marked
Solution to LeetCode 309: Best Time to Buy and Sell Stock with Cooldown Problem

You are given an integer array ‘prices’, where ‘prices[i]’ represents the price of a stock on the i-th day. You are allowed to complete as many transactions as you like, with the restriction that after selling a stock, you cannot buy again the next day (cooldown). The goal is to calculate the maximum profit you can achieve by making any number of transactions while respecting the cooldown period.
Problem
Approach
Steps
Complexity
Input: The input consists of an integer array, 'prices', where each element represents the price of a stock on a specific day.
Example: prices = [1, 2, 3, 0, 2]
Constraints:
• 1 <= prices.length <= 5000
• 0 <= prices[i] <= 1000
Output: The output is the maximum profit achievable by making transactions while respecting the cooldown period.
Example: For prices = [1, 2, 3, 0, 2], the output is 3.
Constraints:
Goal: To find the maximum profit achievable by completing multiple stock transactions while adhering to the cooldown constraint.
Steps:
• Use dynamic programming to track the states: whether we are holding a stock or not, and whether we're in a cooldown period.
• For each day, decide whether to buy, sell, or cooldown based on the previous decisions.
• Memoize the results to avoid redundant calculations and improve efficiency.
Goal: The solution needs to handle large inputs efficiently within the given constraints.
Steps:
• The array can have up to 5000 elements.
• The price of the stock can be between 0 and 1000.
Assumptions:
• The solution should handle edge cases like no profit or small arrays.
Input: prices = [1, 2, 3, 0, 2]
Explanation: The optimal transaction sequence is to buy on day 1 and sell on day 2, then cooldown on day 3, then buy on day 4 and sell on day 5. The total profit is 3.

Input: prices = [5, 1, 3, 6, 4]
Explanation: The optimal sequence is to buy on day 2, sell on day 3, buy on day 4, and sell on day 5. The total profit is 7.

Input: prices = [1]
Explanation: With only one price, no transaction is possible, and the maximum profit is 0.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus