-
Notifications
You must be signed in to change notification settings - Fork 0
/
122.best-time-to-buy-and-sell-stock-ii.js
107 lines (51 loc) · 1.59 KB
/
122.best-time-to-buy-and-sell-stock-ii.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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/*
* @lc app=leetcode id=122 lang=javascript
*
* [122] Best Time to Buy and Sell Stock II
*/
// @lc code=start
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
};
maxProfit([1,2,3,4,5]);
// @lc code=end
/* greedy
let min = prices[0];
let profit = 0;
for (let i = 1; i < prices.length; i++) {
const price = prices[i];
if (price > min) {
profit += price - min;
min = price;
} else {
min = Math.min(min, price);
}
}
return profit;
let output = 0;
if(prices.length>0){
prices.reduce((acc,next)=>{
if(next>acc){
output += next-acc
}
return next;
})
}
return output;
*/
/* bottom-up DP + iteration
// It is impossible to sell stock on first day, set -infinity as initial value for curHold
let [curHold, curNotHold] = [-Infinity, 0];
for(const stockPrice of prices){
let [prevHold, prevNotHold] = [curHold, curNotHold];
// either keep hold, or buy in stock today at stock price
curHold = Math.max(prevHold, prevNotHold - stockPrice );
// either keep not-hold, or sell out stock today at stock price
curNotHold = Math.max(prevNotHold, prevHold + stockPrice );
}
// Max profit must come from notHold state finally.
return curNotHold;
*/