Skip to content

Instantly share code, notes, and snippets.

@oney
Created July 28, 2015 10:11
Show Gist options
  • Save oney/4233d46935fbf2663201 to your computer and use it in GitHub Desktop.
Save oney/4233d46935fbf2663201 to your computer and use it in GitHub Desktop.
Get highest profit
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