Skip to content

Commit aa5b8b8

Browse files
committed
implement: 122
1 parent 5e1a4b4 commit aa5b8b8

File tree

1 file changed

+46
-1
lines changed
  • src/best-time-to-buy-and-sell-stock-ii

1 file changed

+46
-1
lines changed

src/best-time-to-buy-and-sell-stock-ii/res.js

+46-1
Original file line numberDiff line numberDiff line change
@@ -26,4 +26,49 @@ var maxProfit = function(prices) {
2626
}
2727

2828
return res;
29-
};
29+
};
30+
31+
/**
32+
* 一次遍历
33+
* @param {*} prices
34+
*/
35+
var maxProfit = function(prices) {
36+
const len = prices.length;
37+
if (len < 2) return 0;
38+
let res = 0;
39+
40+
for (let i = 1; i < len; i++) {
41+
const temp = prices[i] - prices[i-1];
42+
if (temp > 0) {
43+
res += temp;
44+
}
45+
}
46+
47+
return res;
48+
}
49+
50+
/**
51+
* 找到每次单调进行处理
52+
* @param {*} prices
53+
*/
54+
var maxProfit = function(prices) {
55+
const len = prices.length;
56+
if (len < 2) return 0;
57+
let res = 0;
58+
let peak = prices[0], valley = prices[0];
59+
60+
let i = 1;
61+
while (i < len) {
62+
while (i < len && prices[i] - prices[i-1] <= 0) {
63+
i++;
64+
}
65+
valley = prices[i-1];
66+
while (i < len && prices[i] - prices[i-1] >= 0) {
67+
i++;
68+
}
69+
peak = prices[i-1];
70+
res += peak - valley;
71+
}
72+
73+
return res;
74+
}

0 commit comments

Comments
 (0)