-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsolution.js
26 lines (23 loc) · 888 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
const maxProfit = prices => {
let maximumProfit = -1;
prices.forEach((price, index) => {
const profit = Math.max(...prices.slice(index + 1)) - price;
maximumProfit = profit > 0 && profit > maximumProfit ? profit : maximumProfit;
});
return maximumProfit;
};
const maxProfitLoop = prices => {
let maximumProfit = -1;
let minimumPrice = prices[0];
for (let i = 1; i < prices.length; i++) {
maximumProfit = Math.max(maximumProfit, prices[i] - minimumPrice);
minimumPrice = Math.min(minimumPrice, prices[i]);
}
return maximumProfit > 0 ? maximumProfit : -1;
};
const maxProfitReduce = prices =>
prices.reduce((maximumProfit, price, index, array) => {
const profit = Math.max(...array.slice(index + 1)) - price;
return profit > 0 && profit > maximumProfit ? profit : maximumProfit;
}, -1);
export { maxProfit, maxProfitLoop, maxProfitReduce };