Skip to content

Instantly share code, notes, and snippets.

@philwilt
Last active August 29, 2015 14:10
Show Gist options
  • Save philwilt/bbee3a9158a6d0a18741 to your computer and use it in GitHub Desktop.
Save philwilt/bbee3a9158a6d0a18741 to your computer and use it in GitHub Desktop.
stock_prices
def analyze_stocks(prices)
best_buy_day = nil
best_sell_day = nil
max_profit = 0
prices.each_with_index do |buy_price, buy_day|
prices.slice(buy_day..prices.length).each_with_index do |sell_price, sell_day|
profit = sell_price - buy_price
if profit > max_profit
best_sell_day = buy_day + sell_day + 1
best_buy_day = buy_day + 1
max_profit = profit
end
end
end
[best_buy_day, best_sell_day, max_profit]
end
prices = [10,20,4,5,16,1,25,7,0]
puts analyze_stocks(prices).to_s
# prints [6, 7, 24]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment