The Personal Blog of Todd Sharp

Brain Teaser: Calculate Max Stock Profit

Posted By: Todd Sharp on 3/27/2017 7:52 UTC
Tagged: Brain Teasers, Groovy

I came across an interesting puzzle to solve via interviewcake:

Suppose we could access yesterday's stock prices as an array, where:
  • The values are the price in dollars of Apple stock.
  • A higher index indicates a later time.

So if the stock cost $500 at 10:30am and $550 at 11:00am, then:

stockPricesYesterday[60] = 500;

Write an efficient function that takes stockPricesYesterday and returns the best profit I could have made from 1 purchase and 1 sale of 1 Apple stock yesterday.

For example:

int[] stockPricesYesterday = new int[]{10, 7, 5, 8, 11, 9};
// returns 6 (buying for $5 and selling for $11)

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).

Thinking through the issue leads me to the following thought process:

  1. Loop each 'time of day' slot.
  2. Gather a list of the remaining time slot's prices.
  3. Filter that list to only those greater than the current price.
  4. Get the max of that filtered list.
  5. Subtract the current time slot price from the 'max' future price.
  6. If the result is greater than the previous iteration, set that difference as the new 'max' profit.
  7. Return the 'max' profit.

And here's how that looks in code:

Feel free to share your solution in the comments below.  I'd love to see how you would solve this problem.