-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path123.js
More file actions
43 lines (37 loc) · 1.09 KB
/
123.js
File metadata and controls
43 lines (37 loc) · 1.09 KB
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
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
const _maxProfit1 = (start, end) => {
if (end - start <= 1) return 0;
if (prices[start] >= prices[start + 1]) return _maxProfit1(start + 1, end);
let maxIndex = start + 1;
let maxValue = prices[start + 1];
for (let i = start + 2; i < end; ++i) {
if (prices[i] > maxValue) {
maxIndex = i;
maxValue = prices[i];
}
}
let minIndex = start;
let minValue = prices[start];
for (let i = start + 2; i < maxIndex; ++i) {
if (prices[i] < minValue) {
minIndex = i;
minValue = prices[i];
}
}
return Math.max(maxValue - minValue, _maxProfit1(maxIndex + 1, end));
}
let maxProfitBeforeI = [];
let maxProfitAfterI = [];
let result = 0;
for (let i = 0; i < prices.length; ++i) {
maxProfitBeforeI[i] = _maxProfit1(0, i);
maxProfitAfterI[i] = _maxProfit1(i, prices.length);
const currentProfit = maxProfitBeforeI[i] + maxProfitAfterI[i];
if (currentProfit > result) result = currentProfit;
}
return result;
};