2Brute2Best
🔥0

Best Time to Buy and Sell Stock

Easy·LeetCode #121Basic Anchor
LeetCode
30-Second Mental ModelKadane / Subarray — running minimum (Stock buy / sell, Basic Anchor)
Complexity:O(N^2)→O(N)
Key Insight

Walk the days once and keep the cheapest price so far. For each day, selling there at the cheapest earlier price is the best sale that day. Keep the largest such profit.

Core Validity Invariant

A sale is valid only when the buy came before the sale, so minPrice is taken only from earlier days. That is why the sale check runs before today's price joins the minimum.

01

Problem

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

Return the largest profit you can make. If no profit is possible, return 0, because doing nothing is allowed.

Input

An integer array prices.

Output

The largest profit from one buy and one later sell, or 0 if no profit is possible.

Example 1
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5

Buy at price 1 (index 1) and sell at price 6 (index 4). The profit is 6 − 1 = 5. Buying at 7 (index 0) never helps, because every later price is lower.

Example 2
Input: prices = [7, 6, 4, 3, 1]
Output: 0

The price only falls, so every sale would lose money. Doing nothing gives 0.

Constraints
  • • 1 ≤ prices.length ≤ 10^5
  • • 0 ≤ prices[i] ≤ 10^4
02

First, think yourself

Before opening any solution, try to answer these on paper. Use hints only when stuck — each hint is counted.

  1. 1.

    Can I sell on a day before I bought? What does the order of the days change?

  2. 2.

    If I know the cheapest price up to day 4, what else do I need to find the best sale on day 4?

  3. 3.

    Do I need to compare every pair of days, or can I remember one number from the past?

  4. 4.

    What should the answer be when the prices only go down?

  5. 5.

    How is this different from subtracting the smallest price in the array from the largest one?

03

Brute force approach

05

Optimized approach

06

Why does this algorithm work?

07

Dry run

08

All approaches compared

ApproachIdeaTimeSpace
Brute ForceCheck every pair of days i < j and keep the best profitO(N^2)O(1)
OptimalWalk once; keep the lowest price seen; profit today = price − lowestO(N)O(1)
09

Why does this belong to this pattern?

Clues in the problem statement
  • “buy one share and sell it later”One buy, then one sell, and the sell must come after the buy: the order of the days matters.
  • “largest profit”One sale's profit is today's price minus the cheapest earlier price, so it can be tracked in O(1) per day.
  • “return 0 if no profit”Starting best at 0 handles falling prices without a special case.
one buy before one sell+profit = sell price − buy price+buy price = cheapest earlier price→Kadane / Subarray — running minimum (Stock buy / sell, Basic Anchor)

This is the anchor of the Stock buy / sell sub-pattern. The sell day decides the profit, and for a fixed sell day the best buy is the lowest price before it, so one running minimum is enough. The rule here allows only one trade, so there is one minimum and one maximum. The next two questions keep the same walk but change the rule: many trades (LC 122), then a cooldown after each sale (LC 309).

10

Don't make this mistake

Pattern confusion: max minus min ignores the order of the days
✗ return *max_element(prices.begin(), prices.end()) - *min_element(prices.begin(), prices.end());
✓ int minPrice = prices[0], best = 0; // then walk the days, as in the optimal

On [7, 1, 5, 3, 6, 4], the biggest price is 7 (day 0) and the smallest is 1 (day 1). 7 − 1 = 6 would sell on day 0 before buying on day 1, which is not allowed. The real answer is 5 (buy at 1, sell at 6). On [5, 9, 1, 3] it gives 9 − 1 = 8, but the 9 comes before the 1. The real answer is 4 (buy at 5, sell at 9).

Starting best at the first price change
✗ int best = prices[1] - prices[0];
✓ int best = 0;

On [7, 6, 4, 3, 1] the first change is 6 − 7 = −1, so this returns −1. Doing nothing is allowed, so the answer must be 0.

Comparing each day only with the day before
✗ best = max(best, prices[i] - prices[i - 1]);
✓ best = max(best, prices[i] - minPrice);

On [7, 1, 5, 3, 6, 4] the largest single-day change is 4 (from 1 to 5), so this returns 4. The real answer is 5, which buys at 1 and sells at 6, two days apart. A profit can span many days, so compare with the cheapest earlier price, not just yesterday.

11

Want to implement this?

Write it yourself on LeetCode, then come back and compare your code with the solutions above.

Open coding workspace
How did it go?
Beyond The LeetCode Problem

How this concept connects to System Design & C++ Systems

Bridge DSA with production engineering

Top engineering interviews test whether you understand how algorithms like DP — Kadane / Subarray translate into production architectures and low-level memory mechanics.