-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path121.js
More file actions
32 lines (28 loc) · 776 Bytes
/
121.js
File metadata and controls
32 lines (28 loc) · 776 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
/**
* @param {number[]} prices
* @return {number}
*/
var maxProfit = function(prices) {
const _maxProfit = start => {
if (prices.length - start <= 1) return 0;
if (prices[start] >= prices[start + 1]) return _maxProfit(start + 1);
let maxIndex = start + 1;
let maxValue = prices[start + 1];
for (let i = start + 2; i < prices.length; ++i) {
if (prices[i] > maxValue) {
maxIndex = i;
maxValue = prices[i];
}
}
let minIndex = start;
let minValue = prices[start];
for (let i = start + 1; i < maxIndex; ++i) {
if (prices[i] < minValue) {
minIndex = i;
minValue = prices[i];
}
}
return Math.max(maxValue - minValue, _maxProfit(maxIndex + 1));
}
return _maxProfit(0);
};