You are given prices, where prices[i] is what one share of a stock costs on day i.
You may make at most one trade: buy one share on some day, then sell it on a strictly later day. Return the largest profit that trade can earn. If every possible trade loses money or breaks even, do nothing and return 0.
Example 1
Input: prices = [3, 8, 2, 6, 9, 4] Output: 7 Why: buy at 2 on day 2, sell at 9 on day 4
2 more examples and the constraints
Example 2
Input: prices = [9, 7, 4, 1] Output: 0 Why: the price only falls, so skip trading
Example 3
Input: prices = [5] Output: 0 Why: one day leaves no later day to sell on
Constraints
- 1 ≤ length of prices ≤ 100,000
- 0 ≤ each price ≤ 10,000
Your turn first
Have a go on paper or in your own editor, then reveal the approaches from the simplest up.
- Brute forceO(n²)
- One pass, cheapest so farO(n)
The idea in one sentence
The pattern, how to spot it, and the best complexity.
Side by side
| Approach | Time | Relative work for 100,000 days | Verdict |
|---|---|---|---|
| Brute force | O(n²) | Mention it, then move on | |
| One pass, cheapest so far | O(n) | Best; one pass, no memory |
n = how many days of prices there are.
Edge cases to test
- Prices only fall. [9, 7, 4, 1] has no profitable trade, so the answer is 0, never a negative number.
- One day. [5] has no later day to sell on; return 0.
- Cheapest day comes last. [4, 6, 1] must still give 2. A new low late in the list only helps sales after it.
- Best sale is not after the lowest price. [2, 9, 1, 3] gives 7. The overall minimum 1 is a trap: max minus min would say 8.
- Flat prices. [6, 6, 6] gives 0.
Common mistakes
- Returning the overall maximum minus the overall minimum, ignoring that the buy must come first.
- Starting best at a negative number or at prices[1] − prices[0], so a falling market returns a loss instead of 0.
- Resetting best when a new lowest price shows up. A profit already found still counts, even if a cheaper day comes later.
How to talk through it
- 1Clarify. Exactly one buy and one sell? Must the sell be on a later day? What do I return if no trade makes money?
- 2Give the brute force. Try every buy day with every later sell day; O(n²), too slow for 100,000 days.
- 3Fix the sell day. If I sell today, the best buy is the cheapest price before today. A running minimum gives that in O(1).
- 4Code the one pass. Update the minimum, then the best profit; start best at 0 so not trading is allowed.
- 5Test out loud. Run a falling list, a single day, and [2, 9, 1, 3] where the global minimum is a trap.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?