Skip to content

Instantly share code, notes, and snippets.

@johnpolacek
Last active August 31, 2020 16:52
Show Gist options
  • Save johnpolacek/1f2d0981ad0c78ff43100c51787928c1 to your computer and use it in GitHub Desktop.
Save johnpolacek/1f2d0981ad0c78ff43100c51787928c1 to your computer and use it in GitHub Desktop.
Given an array of numbers that represent stock prices (where each number is the price for a certain day), find 2 days when you should buy and sell your stock for the highest profit.
const stockBuySell = (days) => {
const best = days.reduce((bestResult, price, i) => {
const buyDays = days.slice(i+1)
if (buyDays.length) {
const highest = Math.max.apply(null, days.slice(i+1))
const roi = highest - price
if (roi > bestResult.roi) {
bestResult = {buyDay: i, sellDay: days.indexOf(highest), roi}
}
}
return bestResult
}, {buyDay: 0, sellDay: 1, roi: days[1] - days[0]})
return `buy on day ${best.buyDay+1}, sell on day ${best.sellDay+1}`
}
stockBuySell([110, 180, 260, 40, 310, 535, 695])
// "buy on day 4, sell on day 7"
stockBuySell([695, 110, 180, 260, 40, 310, 535])
// "buy on day 5, sell on day 7"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment