-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path122_maxProfit.js
59 lines (52 loc) · 1.27 KB
/
122_maxProfit.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
// 122. 买卖股票的最佳时机 II.
// https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-ii/
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function (prices) {
const len = prices.length
if (len < 2) {
return 0
}
// 下一天的金额
let next = prices[len - 1]
let shouyi = 0
for (let i = len - 2; i >= 0; i--) {
// 比最大值大的时候,要
shouyi += next - prices[i] > 0 ? next - prices[i] : 0
// 向前移动
next = prices[i]
}
return shouyi
};
// console.log(maxProfit([7, 6, 4, 3, 1]));
/**
* 扩展 如果只可以一次买卖的情况
* @param {*} prices
*/
var maxProfitByOne = function (prices) {
const len = prices.length
if (len < 2) {
return 0
}
// 下一天的金额
let next = prices[len - 1]
let shouyi = 0
let max = 0
for (let i = len - 2; i >= 0; i--) {
// 比最大值大的时候,要
if (next - prices[i] > 0) {
shouyi += next - prices[i]
} else {
shouyi = 0
}
if (shouyi > max) {
max = shouyi
}
// 向前移动
next = prices[i]
}
return max
}
console.log(maxProfitByOne([7, 1, 5, 3, 6, 4]));