Skip to content

Instantly share code, notes, and snippets.

@okovalov
Created February 27, 2019 00:33
Show Gist options
  • Save okovalov/c794c21814597fd0a90eb25e20ffb6fe to your computer and use it in GitHub Desktop.
Save okovalov/c794c21814597fd0a90eb25e20ffb6fe to your computer and use it in GitHub Desktop.
const maxProfit = arr => {
let bestBuyPrice = 1000000
let maxProfit = -1
for(let i = 0; i < arr.length - 1; i++) {
const currentBuyPrice = arr[i]
const nextSellPrice = arr[i+1]
if (currentBuyPrice < bestBuyPrice) bestBuyPrice = currentBuyPrice
const currentProfit = nextSellPrice - bestBuyPrice
if (currentProfit > maxProfit) maxProfit = currentProfit
}
return maxProfit
}
const prices1 = [32, 46, 26, 38, 40, 48, 42] // 22
const prices2 = [10, 18, 4, 5, 9, 6, 16, 12] // 12
const prices3 = [10, 9, 8, 8, 7, 6, 5, 4] // 0
const prices4 = [10, 9, 8, 7, 6, 5, 4, 3] // -1
const res1 = maxProfit(prices1)
console.log(res1) // 22
const res2 = maxProfit(prices2)
console.log(res2) // 12
const res3 = maxProfit(prices3)
console.log(res3) // 0
const res4 = maxProfit(prices4)
console.log(res4) // -1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment