Created
July 28, 2015 10:11
-
-
Save oney/4233d46935fbf2663201 to your computer and use it in GitHub Desktop.
Get highest profit
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
def highest_profit(stock_prices) | |
lowest = buy = sell = stock_prices.shift | |
stock_prices.each do |price| | |
current_profit = sell - buy | |
if (price - lowest) > current_profit | |
buy = lowest | |
sell = price | |
end | |
if price < lowest | |
lowest = price | |
end | |
end | |
{buy: buy, sell: sell, profit: (sell - buy)} | |
end | |
puts highest_profit([5, 6, 4, 7, 9, 8, 8]) # {:buy=>4, :sell=>9, :profit=>5} | |
puts highest_profit([10, 12, 11, 20, 4, 9, 8, 8]) # {:buy=>10, :sell=>20, :profit=>10} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment