Skip to content

Instantly share code, notes, and snippets.

@robinpokorny
Created October 13, 2021 15:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robinpokorny/6cbb5f8f25a9eed44c8fac36bc2a61b8 to your computer and use it in GitHub Desktop.
Save robinpokorny/6cbb5f8f25a9eed44c8fac36bc2a61b8 to your computer and use it in GitHub Desktop.
Most profit from stock quotes [solution] [JS]
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)
}
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