Skip to content
BytePatterns

Trading With Cooldown

HardDynamic Programming#state-machine-dp#rolling-variables~45m

Problem

You are given daily prices for one stock and may trade as often as you like, but you can hold at most one share at a time. After any sale you must sit out the following day entirely, so the earliest possible next purchase is two days later. Return the maximum total profit achievable, which is 0 when no trade is worth making.

Examples

Input:  prices = [1, 2, 3, 0, 2]
Output: 3
Why:    buy at 1, sell at 2, rest a day, buy at 0, sell at 2
Input:  prices = [5, 4, 3]
Output: 0
Why:    every trade would lose money, so no trade is made
Input:  prices = []
Output: 0
Why:    edge case, there are no days to trade on

Hints

0 / 3