Skip to content

Instantly share code, notes, and snippets.

@tjsingleton
Forked from martin2110/apple_stock.rb
Last active October 6, 2015 20:32
Show Gist options
  • Save tjsingleton/942a1f80ef29e4b84df4 to your computer and use it in GitHub Desktop.
Save tjsingleton/942a1f80ef29e4b84df4 to your computer and use it in GitHub Desktop.
stock = [1,8,3,0,1,54,29,1,3,10,49,10,39,28,41,1,3]
prices= Array.new
stock.each_with_index do |buy_price, buy_index|
stock.each_with_index do |sell_price, sell_index|
if buy_index < sell_index
value = sell_price - buy_price
hr = {sell_index: sell_index, buy_index: buy_index, value: value}
prices << hr
end
end
end
max = prices.max_by{|k,v| k[:value] }
puts "Best time to buy was index #{max[:buy_index]} and the best time to sell was index #{max[:sell_index]} total profit was #{max[:value]}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment