Best Time to Buy And Sell Stock With Cooldown
Medium · 2-D Dynamic Programming
You are given a list of daily stock prices, where prices[i] is the price on day i. You may buy and sell the stock any number of times, but you can only hold one share at a time, meaning you must sell before buying again. After you sell, you must wait one full day (a cooldown) before you are allowed to buy again. Return the maximum total profit achievable under these rules.
Examples
Input: prices = [1,2,3,0,2]
Output: 3
Why: Buy at 1, sell at 3 for profit 2, cooldown one day, then buy at 0 and sell at 2 for profit 2, but the cooldown forces the second buy later so the best achievable total is 3.
Input: prices = [1]
Output: 0
Why: There is no day left to sell after buying, so no profit can be made.
Input: prices = [1,2,4]
Output: 3
Why: Buying at 1 and selling at 4 gives the best single trade profit of 3.
Constraints
1 <= prices.length <= 5000, 0 <= prices[i] <= 1000
Practise it by voice
Describe the solution out loud and the interviewer writes exactly what you say, asks when you are vague, and runs the tests in your browser.
Practise Best Time to Buy And Sell Stock With Cooldown
This statement is written for CodeSpeek. The problem is part of the NeetCode 150 list; Watch NeetCode's explanation of Best Time to Buy And Sell Stock With Cooldown. Reference solutions from the NeetCode repository (MIT) are used to verify our tests.