-
Notifications
You must be signed in to change notification settings - Fork 71
/
Copy pathres.js
74 lines (63 loc) · 1.31 KB
/
res.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
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
let min = 999999, max = -1;
let res = 0;
for (let index = 0; index < prices.length; index++) {
const element = prices[index];
if (index === 0 || element < max || min > element) {
if (min !== 999999 && max !== -1) {
res += (max - min);
}
min = element;
max = -1;
} else if (max < element) {
max = element;
}
}
if (min !== 999999 && max !== -1) {
res += (max - min);
}
return res;
};
/**
* 一次遍历
* @param {*} prices
*/
var maxProfit = function(prices) {
const len = prices.length;
if (len < 2) return 0;
let res = 0;
for (let i = 1; i < len; i++) {
const temp = prices[i] - prices[i-1];
if (temp > 0) {
res += temp;
}
}
return res;
}
/**
* 找到每次单调进行处理
* @param {*} prices
*/
var maxProfit = function(prices) {
const len = prices.length;
if (len < 2) return 0;
let res = 0;
let peak = prices[0], valley = prices[0];
let i = 1;
while (i < len) {
while (i < len && prices[i] - prices[i-1] <= 0) {
i++;
}
valley = prices[i-1];
while (i < len && prices[i] - prices[i-1] >= 0) {
i++;
}
peak = prices[i-1];
res += peak - valley;
}
return res;
}