stormwatch / stocks_price

An exercise I am using to learn about profiling and practice TDD

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Stock Prices

What is this?

I’ve been handed an exercise of origin unknown in an interview and I decided to use to practice TDD and to learn about benchmarking and profiling Ruby code. For that I’ll need at least two implementations. The first one is purposely not efficient. The second shall do its thing in one pass. Then I’ll be able to test and compare them.

Original problem statement

Suppose we could access yesterday’s stock prices as an array for stock `Apple`, 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 the stock at that time.

So if the stock costs $500 at 10:30am, stock_prices[60] == 500.

Write an efficient method that takes stock_prices and returns the best profit I could have made from 1 purchase and 1 sell of the stock yesterday.

For example:

stock_prices = [10, 7, 5, 8, 11, 9]

Should return ($6), and you should buy for ($5) at (3rd) min and sell for ($11) at (5th) min

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


I am omitting the original required return value. For the time being I only care about returning the number associated with the profit.


An exercise I am using to learn about profiling and practice TDD

License:MIT License


Language:Ruby 100.0%