Skip to content

Instantly share code, notes, and snippets.

@Em-AK
Last active August 29, 2015 14:26
Show Gist options
  • Save Em-AK/3395de026a6f1dba7997 to your computer and use it in GitHub Desktop.
Save Em-AK/3395de026a6f1dba7997 to your computer and use it in GitHub Desktop.
Trading kata

I have an array stock_prices_yesterday where:

The indices are the time in minutes past trade opening time, which was 9:30am local time. The values are the price in dollars of Apple stock at that time. For example, the stock cost $500 at 10:30am, so stock_prices_yesterday[60] = 500.

Write an efficient algorithm for computing the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday.

No "shorting"—you must buy before you sell. You may not buy and sell in the same time step (at least 1 minute must pass).

Source interviewcake.com

class Trader
attr_accessor :stock_prices
RIDICULOUSLY_HIGH_PRICE = 100_000_000_000
def initialize(stock_prices)
@stock_prices = stock_prices
@min_buy_value = RIDICULOUSLY_HIGH_PRICE
@max_profit = - 8000
end
def max_profit
stock_prices.each.with_index do |sell_value, current_time|
update_max_profit(sell_value, current_time)
end
@max_profit
end
private
def update_max_profit(sell_value, time)
current_profit = sell_value - update_min_buy_value(time)
@max_profit = [@max_profit, current_profit].max
end
def update_min_buy_value(time)
if time > 0
@min_buy_value = [@min_buy_value, stock_prices[time - 1]].min
else
@min_buy_value
end
end
end
require 'minitest/autorun'
require_relative 'appl.rb'
class TestTrader < Minitest::Test
def test_max_profit_return_0_for_a_contstant_stock_price
stock_prices = [500, 500, 500, 500, 500]
jerome = Trader.new(stock_prices)
assert_equal 0, jerome.max_profit
end
def test_max_profit_return_delta_when_one_price_is_higher
stock_prices = [500, 500, 500, 600, 500]
jerome = Trader.new(stock_prices)
assert_equal 100, jerome.max_profit
end
def test_max_profit_is_negative_when_stock_goes_only_down
stock_prices = [900, 800, 700, 600, 500]
jerome = Trader.new(stock_prices)
assert_equal -100, jerome.max_profit
end
def test_max_profit_when_min_after_max
stock_prices = [500, 500, 500, 600, 400]
jerome = Trader.new(stock_prices)
assert_equal 100, jerome.max_profit
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment