Recursion

Max Profit with Cooldown

State-Based Dynamic Programming

Given a list of stock prices, prices, find the maximum profit you can make.

After you sell, you must wait one day before buying again. You can only own 1 stock at a time.

First Few Test Cases:

0. Problem

As usual, we start out not owning any stock and are allowed to buy it. This problem is different because after we sell a stock, we need to cooldown for a day before buying again. We can do this by adding an additional "Cooldown" state, that indicates we just sold the stock and are unable to buy anything the next day. We should just move back to the sold state the next day (where you're allowed to buy stock again). Here's a picture that describes this:

We're looking for the max profit if we're in the Not Own, Own, or Sold With Cooldown states.

1. Recursion

We can look at the arrows that point to each state to find its recursion:

2. Base case

We start out in the Not Own state with 0 profit. We need to assign profits to the other two states so that they'll eventually get overwritten when we can reach those states. We'll just set them to -infinity.

3. Code

Time Complexity O(n)O(n). We iterate through all nn days.

Space Complexity O(1)O(1)

Mark as Completed:
Submits:
cooldownProfit
Test your code to get an output here!
cooldownProfit(
)
Test your code to get an output here!