Data Structures & Algorithms COURSE·LESSON 23 OF 1710 completed
QUESTION-SPECIFIC ANIMATED TRACE016 · 016. Best Time To Buy & Sell StockFollow this problem’s own pseudocode and example.
01function maxProfit(prices):
02 minSoFar=+infinity; best=0
03 for price in prices:
04 minSoFar=min(minSoFar,price)
05 best=max(best,price-minSoFar)
06 return best

For each sale day, the best earlier buy is the minimum price seen so far. Update profit using that minimum.

016. Best Time to Buy and Sell Stock

Roadmap: Day 9 · Sliding Window · Easy

Open the original problem on LeetCode ↗ — use that page for the full statement, constraints, and test runner.

Goal in plain language

Solve Best Time to Buy and Sell Stock as defined by the linked prompt. Before looking at the algorithm, restate the required output, identify what the input guarantees, and note whether the result must preserve order or mutate the input.

Recognize the pattern

This belongs to Sliding Window. The question asks about a contiguous substring/subarray and a condition can be maintained as endpoints move.

Key observation

For each sale day, the best earlier buy is the minimum price seen so far. Update profit using that minimum.

Concepts to understand

  • State: Expand to add information and shrink when invalid (or once valid for a minimum). Each endpoint moves forward at most n times.
  • Invariant: The information already recorded is sufficient to make the next decision without revisiting every earlier choice.
  • Correctness: Each transition either preserves the candidate answers or eliminates a region that cannot contain a better/valid answer.
  • Trade-off: The faster method uses additional state or relies on a structural guarantee; state that assumption explicitly.

Solve it step by step

  1. Translate the prompt into the data model and confirm the edge conditions in the linked statement.
  2. Start with the simplest correct approach; identify where it repeats work.
  3. Use the observation above to retain only the state needed by the next step.
  4. Update that state in a consistent order, then evaluate the answer.
  5. Check the walkthrough and edge cases before coding.

Pseudocode

text
function maxProfit(prices):
    minSoFar=+infinity; best=0
    for price in prices:
        minSoFar=min(minSoFar,price)
        best=max(best,price-minSoFar)
    return best

Walkthrough

For [7,1,5,3,6,4], the minimum becomes 1, and later sale at 6 yields profit 5.

Why it works

Invariant: For each sale day, the best earlier buy is the minimum price seen so far. Update profit using that minimum.

At the end: Applying this observation to the complete input (or to the final maintained boundary) yields the result requested by the linked problem.

Complexity

O(n) time, O(1) space. State any output storage separately.

Edge cases and pitfalls

  • Empty, one-element, and smallest legal input.
  • Repeated values/characters, if the statement permits them.
  • Boundary values and an answer at the first or last position.
  • Specific trap: Return 0 when prices only decrease; a transaction must buy before it sells.
  • Confirm whether indexes are zero-based, one-based, inclusive, or exclusive.

Say it in an interview

“The key observation is: For each sale day, the best earlier buy is the minimum price seen so far. Update profit using that minimum. I maintain the state implied by that observation while processing candidates, which avoids repeating work. The complexity is O(n) time, O(1) space.”

Practice

Re-solve it without notes after a short break, then explain why the optimization is correct.

Learn at your own pace0 / 171 lessons complete