Best Time to Buy and Sell Stock

25 min · maxProfit()

A stock chart makes hindsight look easy. Your code has to make the best legal trade without looking backwards in time.

You're given prices, where prices[i] is one share's price on day i. Choose one day to buy and a later day to sell, then return the largest profit that trade can earn. If every possible trade loses money or breaks even, return 0.

A few ground rules:

  • You may complete at most one buy-and-sell trade.
  • The sale must happen after the purchase; buying and selling on the same day isn't a trade.
  • You return the profit, not the two days.

Constraints

  • 1 <= prices.length <= 100_000
  • 0 <= prices[i] <= 10_000

Hints

Start with every legal trade

Pick each buy day, pair it with every later sell day, and keep the best difference. What work gets repeated when you move to the next sell day?

Ask what a sell day needs

If today is the sell day, only one earlier fact matters: the lowest price seen before today. A more expensive earlier purchase can never produce a better profit today.

Carry two numbers

Scan left to right. Track the cheapest price so far and the best profit so far. Check today's profit before allowing today's price to become a future purchase.

Follow-up

How would your state change if you were allowed to complete as many non-overlapping trades as you wanted?

Visible cases

Examples

Example 1

ready
Input
prices = [
  7,
  1,
  5,
  3,
  6,
  4
]
Expected
5
Why
buy at 1, then sell later at 6

Example 2

ready
Input
prices = [
  7,
  6,
  4,
  3,
  1
]
Expected
0
Why
every later price is lower, so skipping the trade wins

Example 3

ready
Input
prices = [
  2,
  4,
  1
]
Expected
2
Why
the 2-to-4 trade earns more than anything after the late dip

Interview signal

Asked at

AmazonGoogleMetaBloomberg
Loading editor

Console

ready to run

Ready to run.

3 cases are queued.

Run: visible + custom · Submit: full suite