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 == 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.
stock_prices = [10, 7, 5, 8, 11, 9] get_max_profit(stock_prices)
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.