Buy/Sell

Given a list of stock prices (ordered by time), we want to write a function for the max profit you can make from buying the stock at one point in time, and selling it a later point in time.

In the example below, we'd return a profit of $10 by buying at $1 and selling at $11.

Function: buy_sell(prices: Number[])
Input: [3, 5, 1, 7, 8, 10, 11, 2]
Output: [10, 1, 11]
Example: buy_sell([3, 5, 1, 7, 8, 10, 11, 2]) == [10, 1, 11]

Requirements:

  • You cannot buy and sell in the same day
  • You must buy before you sell (i.e. no shorts)
  • You must make exactly 1 trade
  • If the prices are decreasing, we'd minimize loss (return the least negative profit)
  • Stock prices will always be an array of positive integers, with at least 2 prices
  • Output format: [<profit>, <purchase_price>, <sell_price>]

Space constraints: O(n), n = # of prices

Run time constraints: None. There is no penalty for greater than O(n) run time. In fact, we prefer arriving more quickly at a solution that's optimized for readability, NOT run time.