Proficient Level

Implement the maxProfitWithCooldown method that returns the maximum stock profit with a one-day cooldown after selling.

You are given an array where each value represents the price of a stock on that day. You may buy and sell multiple times, but after selling a stock, you must wait one day before buying again.

Return the maximum profit possible. You may hold at most one stock at a time.

Example 1

Input
prices (int[]) = [1,2,3,0,2]
size (int) = 5
Returns (int) 3

Example 2

Input
prices (int[]) = [1]
size (int) = 1
Returns (int) 0

Example 3

Input
prices (int[]) = [6,1,6,4,3,0,2]
size (int) = 7
Returns (int) 7

Track the best result for three states: holding a stock, just sold a stock, and resting without stock.

If you are holding, you either kept holding from the previous day or bought today from a rest state. If you sold today, you must have been holding yesterday. If you are resting, you either continued resting or came from the sold state after cooldown.

The answer is the best profit when not holding stock at the end.

Pseudocode:

function maxProfitWithCooldown(prices, size):
    hold = -prices[0]
    sold = 0
    rest = 0
    for i from 1 to size - 1:
        previousHold = hold
        previousSold = sold
        previousRest = rest
        hold = max(previousHold, previousRest - prices[i])
        sold = previousHold + prices[i]
        rest = max(previousRest, previousSold)
    return max(sold, rest)
Ready to test your solutionRun Code checks your solution against the test cases.Shift + Enter to run

Notifications

Updates are enabled for this browser.

Receive new tutorials, articles and learning resources. You can turn updates off anytime.

Test browser code

Use this code in admin to send a test notification to this browser.