-
Notifications
You must be signed in to change notification settings - Fork 6
/
309. Best Time to Buy and Sell Stock with Cooldown.js
65 lines (60 loc) · 1.53 KB
/
309. 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
64
65
/**
* @param {number[]} prices
* @return {number}
*/
// recursion
var maxProfit = function (prices) {
if (prices.length <= 1) {
return 0;
}
var max = 0;
var count = 0;
var helper = function (curPrice, profit, idx, cooldown, ops) {
if (idx === prices.length) {
// console.log(ops);
count++;
if (profit > max) {
return (max = profit);
}
return;
}
var today = prices[idx];
if (cooldown) {
helper(null, profit, idx + 1, false, ops.concat("cooldown"));
} else {
if (curPrice === null) {
helper(today, profit, idx + 1, false, ops.concat("buy"));
helper(curPrice, profit, idx + 1, false, ops.concat("hold"));
} else {
helper(
null,
profit + today - curPrice,
idx + 1,
true,
ops.concat("sell")
);
helper(curPrice, profit, idx + 1, false, ops.concat("hold"));
}
}
};
helper(null, 0, 0, false, []);
// console.log("count:", count);
return max;
};
// state machine
var maxProfit = function (prices) {
var noStock = 0;
var inHand = -prices[0];
var sold = 0;
for (let i = 1; i < prices.length; i++) {
inHand = Math.max(inHand, noStock - prices[i]);
noStock = Math.max(noStock, sold);
sold = Math.max(sold, inHand + prices[i]);
}
return sold;
};
// console.log(maxProfit([1, 2, 3, 0, 2]));
// console.log(maxProfit([3, 2, 6, 5, 0, 3]));
// console.log(maxProfit([1, 2]));
// console.log(maxProfit([2, 1, 4]));
// console.log(maxProfit([1, 2, 4]));