|
| 1 | +export {}; |
| 2 | + |
| 3 | +/** |
| 4 | +For each day we have three different multi universe, which we |
| 5 | + 1. just sell in this day |
| 6 | + 2. just buy in this day |
| 7 | + 3. just do noop this day |
| 8 | +
|
| 9 | +So how come we deal with each relation? |
| 10 | +
|
| 11 | +As the desc, we are |
| 12 | + 1. not allowed to buy after we sell (cooldown) |
| 13 | + 2. not allowed hold multiple shares |
| 14 | +
|
| 15 | +
|
| 16 | +So now we had three state: |
| 17 | + 1. HOLD -> you had one share in your hand |
| 18 | + 2. RELEASE -> you just sell that share (so I mean you need to at hold state in previous day) |
| 19 | + 3. IDLE -> you do nothing, and you don't have the share in your hand. |
| 20 | +
|
| 21 | +The state machine be like |
| 22 | +
|
| 23 | + HOLD[i] = IDLE[i-1] - prices[i] vs HOLD[i-1]; // best buy point |
| 24 | +
|
| 25 | + RELEASE[i] = HOLD[i-1] + prices[i]; |
| 26 | +
|
| 27 | + IDLE[i] = IDLE[i-1] vs RELEASE[i-1] |
| 28 | +
|
| 29 | + */ |
| 30 | + |
| 31 | +// O(n) time, O(n) space, for O(1) space, check the `best-time-to-buy-and-sell-stock-with-cooldown-optimize` |
| 32 | +function maxProfit(prices: number[]): number { |
| 33 | + const N = prices.length; |
| 34 | + |
| 35 | + const hold = Array.from({ length: N }, () => 0); |
| 36 | + const release = Array.from({ length: N }, () => 0); |
| 37 | + const idle = Array.from({ length: N }, () => 0); |
| 38 | + |
| 39 | + if (N < 2) return 0; |
| 40 | + |
| 41 | + hold[0] = -prices[0]; |
| 42 | + release[0] = Number.MIN_SAFE_INTEGER; |
| 43 | + idle[0] = 0; |
| 44 | + |
| 45 | + for (let i = 1; i < N; i++) { |
| 46 | + hold[i] = Math.max(hold[i - 1], idle[i - 1] - prices[i]); |
| 47 | + release[i] = hold[i - 1] + prices[i]; |
| 48 | + idle[i] = Math.max(idle[i - 1], release[i - 1]); |
| 49 | + } |
| 50 | + |
| 51 | + return Math.max(release[N - 1], idle[N - 1]); |
| 52 | +} |
0 commit comments