Best Time to Buy and Sell Stock

easySliding Window22 stepsJava · Python · C++

Buy once, sell once later, maximise profit. Scan left to right keeping the cheapest price so far; selling today earns price - minSoFar. The best of those is the answer.

▶ Watch the animated trace

Traced input: prices = [7, 1, 5, 3, 6, 4] → 5. Original problem: neetcode.io/problems/buy-and-sell-crypto

Complexity

BestO(n)
AverageO(n)
WorstO(n)
SpaceO(1)

One pass, two variables.

Key idea

Common mistakes

Solution

Java
int maxProfit(int[] prices) {
    int minPrice = Integer.MAX_VALUE, best = 0;
    for (int i = 0; i < prices.length; i++) {
        minPrice = Math.min(minPrice, prices[i]);
        best = Math.max(best, prices[i] - minPrice);
    }
    return best;
}
Python
def maxProfit(prices: List[int]) -> int:
    min_price, best = float("inf"), 0
    for p in prices:
        min_price = min(min_price, p)
        best = max(best, p - min_price)
    return best
C++
int maxProfit(vector<int>& prices) {
    int minPrice = INT_MAX, best = 0;
    for (int p : prices) {
        minPrice = min(minPrice, p);
        best = max(best, p - minPrice);
    }
    return best;
}

Edge cases

Each one has its own trace in the interactive view.

CaseInputAnswer
Prices only fall
No profitable trade, so don't trade.
prices = [7, 6, 4, 3, 1]0
Single day
You can't buy and sell on different days.
prices = [5]0
Max before min
9 − 1 isn't allowed (wrong order); 3 − 1 = 2 is.
prices = [9, 1, 3]2
Flat prices
Every trade earns 0.
prices = [3, 3, 3]0
Best at the end
The minimum moves to 1, then 7 − 1 = 6 beats 4 − 2.
prices = [2, 4, 1, 7]6
← Trapping Rain WaterLongest Substring Without Repeating Characters →