Best Time to Buy and Sell Stock with Cooldown

Medium · Dynamic Programming · Array · Dynamic Programming

Problem

You are given prices, where prices[i] is the price of a stock on day i. You may complete as many transactions as you like, under two rules:

Return the maximum profit you can achieve. Doing nothing earns 0.

Examples

Input: prices = [2,6,1,1,5]
Output: 8

Buy on day 0, sell on day 1 (+4), cool down on day 2, buy on day 3, sell on day 4 (+4).

Input: prices = [3,1,4,2,6]
Output: 5

Buy at 1 and hold to 6. Selling at 4 first would force a cooldown on the day the price is 2.

Input: prices = [7]
Output: 0

With a single day nothing can be sold.

Constraints

Approaches

Follow-up

What if each sale also paid a fixed fee? Subtract the fee in the "sold" transition; the three states stay the same. And for a cooldown of k days, "rest" needs to remember sales from k + 1 days back instead of one.

Related problems

Start free on Cariara · Coding problems · System design studio

Starting Python
No results yet.

          
↑↓ move ↵ open esc close

Labs

Loading labs…

Run with your own input

Starting Python

Loading Python…