Practice · Sliding window · 1 of 4

Best Single Trade

You are given prices, where prices[i] is the price of a share on day i. You may buy one share on one day and sell it on a later day.

Return the largest profit you can make. If no trade makes money, return 0 (you simply don't trade).

Example 1

Input
prices = [8, 3, 6, 1, 5, 4]
Output
4
Buy at 1 on day 3 and sell at 5 on day 4.

Example 2

Input
prices = [9, 7, 4, 2]
Output
0
Prices only fall, so the best plan is not to trade.

Constraints

  • prices holds 1 to 10⁵ numbers.
  • Every price is between 0 and 10⁴.