Best Time to Buy and Sell Stock

EasyArrays · Running Minimum🧩 Array ManipulationLeetCode #121 ↗Updated

Problem

You get prices, where prices[i] is a stock's price on day i. You may make one trade: buy on some day and sell on a strictly later day. Return the largest profit you can lock in, or 0 if every possible trade loses money.
Inputprices = [7,1,5,3,6,4]Output5 (buy at 1, sell at 6)
Inputprices = [7,6,4,3,1]Output0 (prices only fall)

1 ≤ n ≤ 105  ·  0 ≤ prices[i] ≤ 104

Try it yourself

Java
class Solution {
    public int maxProfit(int[] prices) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
For any sell day, the best buy day is simply the cheapest day seen so far. Carry that minimum forward and each day becomes a single subtraction.
PatternArray Manipulation

Instinct "In place", "O(1) extra space" or "one pass" over an array? Think write pointer, reversal, prefix/suffix passes or using indices as storage.

Memory hack Read fast, write slow, reverse to rotate, and let the index be the hash.

Open the Array Manipulation guide →

Approaches

Brute ForceTry Every Buy/Sell Pair

Time O(n2)Space O(1)

Fix a buy day i, then try every later sell day j and keep the best prices[j] - prices[i]. Starting the answer at 0 covers the “don't trade” option.

Java
public int maxProfit(int[] prices) {
    int best = 0;
    for (int buy = 0; buy < prices.length; buy++) {
        for (int sell = buy + 1; sell < prices.length; sell++) {
            best = Math.max(best, prices[sell] - prices[buy]);
        }
    }
    return best;
}

Obviously correct, but ~5·109 pair checks at n = 105 times out.

At a glance

LevelApproachTimeSpace
Brute ForceTry Every Buy/Sell PairO(n2)O(1)
BetterSuffix Maximum ArrayO(n)O(n)
OptimalOne Pass — Track the Cheapest DayO(n)O(1)
Common pitfalls
  • Taking max - min of the whole array — the minimum may come after the maximum.
  • Returning a negative number when prices only fall — the answer floors at 0.
  • Pairing a price with a minimum taken from a later day — that sells before buying.
Interview tips
  • Say the brute force in one line, then ask: “for a fixed sell day, which buy day wins?”
  • Name the invariant: minPrice = cheapest price strictly before or on today.
  • Mention the Kadane link — it sets up the multi-transaction follow-ups nicely.
Pattern
Running min/max (prefix state) → best pair (i < j) where the score depends on one earlier and one later element.
My notes saved in this browser