Best single trade

arrays

Best single trade

Robinhood Python Interview Question

Robinhood's education team shows new investors the best profit they could have made from one trade, buying a share on one day and selling it on a later day.

Write a function max_profit(prices) that takes a list of a stock's daily closing prices and returns the largest profit from buying once and then selling once on a later day. Return 0 if no trade makes a profit.

Asked of

  • Data Engineer
  • Data Scientist
  • Analytics Engineer
  • ML Engineer
  • AI Engineer

Example 1

Input

max_profit([7, 1, 5, 3, 6, 4])

Output

5

Example 2

Input

max_profit([7, 6, 4, 3, 1])

Output

0

Explanation

In the first example, buying at 1 on the second day and selling at 6 on the fifth day makes a profit of 5, the best possible. In the second example, the price falls every day, so no trade makes money and the answer is 0.

Submit also runs 3 hidden test cases that check edge cases.