-
Notifications
You must be signed in to change notification settings - Fork 4
/
solution.js
31 lines (25 loc) · 709 Bytes
/
solution.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
"use strict";
const stockPrices = [9, 11, 8, 5, 7, 10];
function findMaximum(startIndex, values) {
let max = null;
for (let i = startIndex; i < values.length; i++) {
if (max === null) max = values[i];
else if (max < values[i]) max = values[i];
}
return max;
}
/**
*
* @param {[number]} values
*/
function solve(values) {
let bestProfit = null;
for (let i = 0; i < values.length - 1; i++) {
const max = findMaximum(i + 1, values);
const profit = max - values[i];
if (bestProfit === null) bestProfit = profit;
else if (bestProfit < profit) bestProfit = profit;
}
return bestProfit;
}
console.log(solve(stockPrices)); // 5