Skip to content

Instantly share code, notes, and snippets.

@woodRock
Last active September 24, 2018 07:00
Show Gist options
  • Save woodRock/b47f5ab793e1cd0675b7f439cbb0f1d6 to your computer and use it in GitHub Desktop.
Save woodRock/b47f5ab793e1cd0675b7f439cbb0f1d6 to your computer and use it in GitHub Desktop.
Given a array of numbers representing the stock prices of a company in chronological order, write a function that calculates the maximum profit you could have made from buying and selling that stock once. You must buy before you can sell it. For example, given [9, 11, 8, 5, 7, 10], you should return 5, since you could buy the stock at 5 dollars …
def maximum_profit stock
max = 0
stock.each_with_index do |buy, i|
(i+1...stock.size).each do |sell|
profit = stock[sell] - buy
max = profit if profit > max
end
end
return max
end
stock = [9, 11, 8, 5, 7, 10]
puts maximum_profit stock
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment