Created
October 13, 2021 15:16
-
-
Save robinpokorny/6cbb5f8f25a9eed44c8fac36bc2a61b8 to your computer and use it in GitHub Desktop.
Most profit from stock quotes [solution] [JS]
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const sum = (a, b) => a + b | |
const getMostProfitFromStockQuotes = (quotes, current = 0) => { | |
if (quotes.length < 2) return current | |
const max = Math.max(...quotes) | |
const maxAt = quotes.indexOf(max) | |
const left = quotes.slice(0, maxAt) | |
const right = quotes.slice(maxAt + 1) | |
const profitOnLeft = left | |
.map(a => max - a) | |
.reduce(sum, 0) | |
return getMostProfitFromStockQuotes(right, current + profitOnLeft) | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const getMostProfitFromStockQuotes = (quotes) => | |
quotes.reduceRight( | |
([max, profit], next) => | |
next > max | |
? [next, profit] | |
: [max, profit + max - next], | |
[-Infinity, 0] | |
)[1]; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment