Command Palette

Search for a command to run...

Problem 32.1 · Advanced DPMedium

Best Time to Buy and Sell Stock with Cooldown

What it teaches: A three-state machine updated daily.

Practise it on judges as “Best Time to Buy and Sell Stock with Cooldown”.

The problem

Unlimited transactions, one share at a time, and after selling you must wait one day before buying again. Return the maximum profit.

Example 1

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

Constraints

  • 1 ≤ n ≤ 5000

Pattern clues in the wording

  • → Buy/sell with a rule that depends on the previous action

These clues point to 1D Dynamic Programming: Define dp[i] as the answer for the first i items, write how it depends on smaller i, and fill it left to right.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int maxProfit(int[] prices) {
        return 0;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
prices = [1,2,3,0,2]
3
2
prices = [1]
0

From slow to fast

Approaches

1

Three-state machine

Time O(n) Space O(1)

hold = max(hold, rest − p); sold = hold + p; rest = max(rest, sold), from yesterday's values.

Approach 1
class Solution {
    public int maxProfit(int[] prices) {
        int hold = Integer.MIN_VALUE / 2, sold = Integer.MIN_VALUE / 2, rest = 0;
        for (int p : prices) {
            int h = Math.max(hold, rest - p);
            int s = hold + p;
            int r = Math.max(rest, sold);
            hold = h; sold = s; rest = r;
        }
        return Math.max(sold, rest);
    }
}

Verdict: Exactly the lesson's machine.

Before you submit

Edge cases and common mistakes

Test these inputs

  • One day (0)
  • Falling prices (0)

Mistakes people make

  • Allowing a buy the day right after a sell.

Interview

Follow-up questions

How do the other stock problems fit the machine?