AAlgoLoopSpaced repetition for LeetCode
MEDIUMDynamic ProgrammingLeetCode ↗

Best Time to Buy and Sell Stock with Cooldown

The key idea

On each day you are in exactly one of three states: holding a stock, having just sold (so tomorrow is a forced cooldown), or resting and free to buy. Track the best profit reachable in each state and let today's states depend only on yesterday's three states. The cooldown is captured by buying only from the resting state, which can never follow a sale by one day.

Problem

You are given an array prices where prices[i] is the price of a given stock on day i. Find the maximum profit you can achieve by completing as many transactions as you like (buy one and sell one share of the stock multiple times) with the following restrictions: after you sell your stock, you cannot buy stock on the next day (that is, there is a one-day cooldown), and you may not engage in multiple transactions at the same time, so you must sell the stock before you buy again. Return the maximum profit; note that you are not allowed to buy and sell on the same day.

Constraints

Examples

Input: prices = [1,2,3,0,2] Output: 3
Input: prices = [1] Output: 0

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Dynamic Programming problems