Maximum Profits

We'll discuss how to write a function that can reap the maximum profits from a day's stock data. We'll discuss both the simple brute-force solution and an elegant solution to this problem.

Maximum Profits


Suppose we could access yesterday’s prices for a certain stock as a chronological list. Write a function that takes the list and returns the highest profit possible from one purchase and one sale of the stock yesterday.

For example, a stock price list of [10, 7, 5, 8, 11, 9] shows that the stock started at 10 and ended at 9, going through the numbers chronologically. There is at least a 1-minute difference between the stock prices.

Taking that array as input, our function should return 6, the maximum possible profit from buying when the price was 5 and selling when the price was 11.

If no profit can be made, return 0.

No “shorting” — you must buy before you sell. You may not buy and sell in the same time step.

Input: Array of Numbers

Output: Number


  • We’ll have to convert this array of stock prices into possible profits.
  • Think about the fact that this is a chronologically ordered list.

Level up your interview prep. Join Educative to access 70+ hands-on prep courses.