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
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjsingleton/942a1f80ef29e4b84df4 to your computer and use it in GitHub Desktop.
Save tjsingleton/942a1f80ef29e4b84df4 to your computer and use it in GitHub Desktop.
# swap loops so we can exit early from the inner loop once we've searched the valid range
require "pp"
require "minitest/autorun"
class StockTest < Minitest::Test
attr_accessor :loops
def pick_best_time_to_buy(stock)
best_value = 0
best_buy_index = 0
best_sell_index = 0
stock.each_with_index do |sell_price, sell_index|
stock.each_with_index do |buy_price, buy_index|
break if buy_index >= sell_index
value = sell_price - buy_price
next if value < best_value
best_value = value
best_buy_index = buy_index
best_sell_index = sell_index
end
end
{value: best_value, buy_index: best_buy_index, sell_index: best_sell_index}
end
def test_picking_best_time_to_buy
stock = [1,8,3,0,1,54,29,1,3,10,49,10,39,28,41,1,3]
max = pick_best_time_to_buy(stock)
assert_equal 3, max[:buy_index]
assert_equal 5, max[:sell_index]
assert_equal 54, max[:value]
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment