Best Time to Buy and Sell Stock
On this page
Problem statement
You are given a list of daily prices for one stock. Choose one day to buy and a later day to sell to make the largest profit, and return that profit. If no profit is possible, return 0. You must buy before you sell, and you make exactly one transaction at most.
It's an easy problem with a pattern you'll reuse constantly: walk once and keep the best thing seen so far (here, the cheapest price) to compare against the current element. Original problem: LeetCode 121.
Example

Input: [7, 1, 5, 3, 6, 4]
Output: 5 # buy at 1 (day 1), sell at 6 (day 4)
Input: [7, 6, 4, 3, 1]
Output: 0 # prices only fall; don't trade
Constraints (assumed)
- 1 ≤ n ≤ 100,000.
- 0 ≤ price ≤ 10,000.
What this question tests
- Replacing an all-pairs search with a running minimum.
- Respecting order: the buy must come before the sell.
- A clean O(n), O(1) solution and a clear explanation of why it's correct.
Questions to ask first
- One transaction, or as many as I like? (Here: one. Unlimited trades is a different, greedy problem.)
- Can I buy and sell on the same day? It gives profit 0, so it doesn't change the answer.
- Return the profit or the days? (Here: the profit; returning days needs two extra variables.)
- What if no profit is possible? (Here: 0.)
Try it yourself first
You have the full problem. Sketch your answer, then sign up free to read the complete walkthrough.
- The complete design, flow by flow, with pictures
- Deep dives into the hard parts
- What mid, senior and staff candidates are expected to say
- Full company question lists
Free forever. No card needed.