This project implements a Ruby method called stock_picker that receives an array of stock prices, one per hypothetical day, and returns the best pair of days to buy and sell to maximize profit.
The method returns an array with two indices [buy_day, sell_day], or an empty array [] when no profitable transaction exists.
We use a single-pass algorithm (O(n) time) that tracks the minimum price seen so far (min_price/min_day) and the maximum profit (max_profit). For each day we compute the profit if we sold that day and update the best pair when a larger profit is found. On ties, the first profitable pair is kept.
- Buy must happen before sell.
- Returns
[]when no profitable trade is possible. - Time complexity: O(n). Space complexity: O(1).
stock_picker([17, 3, 6, 9, 15, 8, 6, 1, 10]) # => [1, 4]
stock_picker([2, 3, 10, 6, 4, 8, 1]) # => [0, 2]
stock_picker([10, 9, 8, 7]) # => []The repository includes specs in spec/stock_picker_spec.rb. To run the tests locally:
bundle install
bundle exec rspec --format documentation- Initialize
min_pricewith the first price andmax_profit = 0. - Iterate prices with index; for each price compute
profit = price - min_price. - If
profit > max_profit, updatemax_profitandbest_days. - If
price < min_price, updatemin_priceandmin_day. - Return
best_daysifmax_profitis positive, otherwise return[].