forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
0309-best-time-to-buy-and-sell-stock-with-cooldown.js
63 lines (49 loc) · 1.63 KB
/
0309-best-time-to-buy-and-sell-stock-with-cooldown.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
* Greedy - State Machine
* Time O(N) | Space O(1)
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
* @param {number[]} prices
* @return {number}
*/
var maxProfit = (prices) => {
let [ sold, held, reset ] = [ (-Infinity), (-Infinity), 0 ];
[ sold, reset ] = search(prices, sold, held, reset);/* Time O(N) */
return Math.max(sold, reset);
}
var search = (prices, sold, held, reset) => {
for (const price of prices) {/* Time O(N) */
const preSold = sold;
sold = (held + price);
held = Math.max(held, (reset - price));
reset = Math.max(reset, preSold);
}
return [ sold, reset ];
}
/**
* DP - Bottom Up
* Array - Tabulation
* Time O(N^2) | Space O(N)
* https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-cooldown/
* @param {number[]} prices
* @return {number}
*/
var maxProfit = (prices) => {
const tabu = initTabu(prices);/* Space O(N) */
search(prices, tabu);/* Time O(N * N) */
return tabu[0];
}
var initTabu = (prices) => new Array(prices.length + 2).fill(0);
var search = (prices, tabu) => {
for (let i = (prices.length - 1); (0 <= i); i--) {/* Time O(N) */
const prev = buyAndSell(prices, i, tabu); /* Time O(N) */
const next = tabu[i + 1];
tabu[i] = Math.max(prev, next); /* Space O(N) */
}
}
const buyAndSell = (prices, i, tabu, max = 0) => {
for (let sell = (i + 1); (sell < prices.length); sell++) {/* Time O(N) */
const profit = ((prices[sell] - prices[i]) + tabu[(sell + 2)]);
max = Math.max(max, profit);
}
return max;
}