-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBestTimeToBuyAndSellStockII.V1.js
More file actions
40 lines (35 loc) · 978 Bytes
/
BestTimeToBuyAndSellStockII.V1.js
File metadata and controls
40 lines (35 loc) · 978 Bytes
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
// https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-iii/
var Test = require('./Common/Test');
var maxProfit = function (prices) {
prices.push(0);
let segments = [];
let segment = [prices[0], prices[0]];
for (let i = 1; i < prices.length; i++) {
const price = prices[i];
if (price > segment[1]) {
segment[1] = price;
}
else {
if (segment[0] != segment[1]) {
segments.push(segment);
}
segment = [price, price];
}
}
return segments.map(([a, b]) => b - a).reduce((sum, val) => sum + val, 0);
};
function test(prices) {
Test.test(maxProfit, prices);
}
test([7, 1, 5, 3, 6, 4]);
test([7, 6, 4, 3, 1]);
test([3, 3, 5, 0, 0, 3, 1, 4]);
test([1, 2, 3, 4, 5]);
// test([7, 6, 4, 3, 1]);
test([1, 2, 3, 0, 2]);
// [7, 1, 5, 3, 6, 4]
// [7, 6, 4, 3, 1]
// [3, 3, 5, 0, 0, 3, 1, 4]
// [1, 2, 3, 4, 5]
// [7, 6, 4, 3, 1]
// [1, 2, 3, 0, 2]