Browse curriculum

Best Time to Buy and Sell Stock (LeetCode 121)

Best Time to Buy and Sell Stock (LeetCode 121): find the best profit from one buy followed by one later sell.

Examples

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

Buy on day 1 at 1 and sell on day 4 at 6.

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

The price only falls, so no transaction makes money.

Input:prices = [3,8,1,4]
Output:5
Explain:

The cheapest day, 1, comes too late: the best sale is still 3 to 8.

Problem Understanding

prices[i] is a stock's price on day i. You may make one trade: buy on a single day, then sell on a later day.

Return the largest profit that one trade can earn, or 0 if every possible trade would lose money.

Strategy

Walk the prices once, carrying two numbers: the cheapest price so far, the only buy price worth considering for a sale today, and the best profit so far, the largest price - min_price seen on any day.

  • Start with min_price = infinity and max_profit = 0.

  • For each price, lower the minimum: min_price = min(min_price, price).

  • Then raise the best: max_profit = max(max_profit, price - min_price).

  • Return max_profit.

Interactive Visualization

ONE COLUMN PER DAY · MIN = CHEAPEST SO FAR · SELL = PRICE − MIN · OUTLINED = THE BUY DAY THIS SALE IS MEASURED AGAINST

NOTHING SEEN YET

0

1

2

3

4

5

price

7
1
5
3
6
4

min

-
-
-
-
-
-

sell

-
-
-
-
-
-

cheapest so far

:

best profit

0

Answer

:

every day

min = the smaller of min and today's price
best = the larger of best and price − min

 

Nothing has been seen yet: the cheapest price is infinite and the best profit is 0

Next

Day 0: the price is 7

Free preview: the first 6 of 20 steps

prices

The lesson's own dry-run table, filling in. Each column is a day: its price, the cheapest price up to that day, and what selling that day would make. The buy day a sale is measured against is outlined in the price row, so every profit is visibly this cell minus that cell.

Try Late low: the cheapest day comes after the best sale, and the answer is unaffected.

Dry Run

prices = [7, 1, 5, 3, 6, 4], days counted from 0 as in the figure:

Day Price Min price so far Sell today (price - min) Max profit
0 7 7 7-7=0 0
1 1 1 1-1=0 0
2 5 1 5-1=4 4
3 3 1 3-1=2 4
4 6 1 6-1=5 5
5 4 1 4-1=3 5

Buy on day 1 at 1, sell on day 4 at 6, return 5.

Edge Cases & Common Mistakes

Watch out for these:

  • A falling market answers 0. If no day is cheaper than a later one, return 0: never a negative profit.

  • The cheapest day is not always part of the answer. In [3, 8, 1, 4] the minimum, 1, arrives after the best sale. Tracking the best profit as you go, not just the minimum, is what handles it.

  • You cannot sell before you buy. Updating the minimum before computing today's sale makes a same-day trade worth 0, so it can never be counted as profit.

  • Unlimited transactions is a different problem. If you may buy and sell many times, add every daily rise instead: see Best Time to Buy and Sell Stock II.

Solution

One pass, two running values: the lines light up as the figure above steps.

Best Time to Buy and Sell Stock Code
1var maxProfit = function(prices) {
2 let minPrice = Infinity;
3 let maxProfit = 0;
4 for (const price of prices) {
5 minPrice = Math.min(minPrice, price);
6 maxProfit = Math.max(maxProfit, price - minPrice);
7 }
8 return maxProfit;
9};

Best Time to Buy and Sell Stock in Python, Java, C++, TypeScript and C

Best Time to Buy and Sell Stock in Python
class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        min_price = float('inf')
        max_profit = 0
        for price in prices:
            min_price = min(min_price, price)
            max_profit = max(max_profit, price - min_price)
        return max_profit
Best Time to Buy and Sell Stock in Java
class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = Integer.MAX_VALUE;
        int maxProfit = 0;
        for (int price : prices) {
            minPrice = Math.min(minPrice, price);
            maxProfit = Math.max(maxProfit, price - minPrice);
        }
        return maxProfit;
    }
}
Best Time to Buy and Sell Stock in C++
class Solution {
public:
    int maxProfit(vector<int>& prices) {
        int minPrice = INT_MAX;
        int maxProfit = 0;
        for (int price : prices) {
            minPrice = min(minPrice, price);
            maxProfit = max(maxProfit, price - minPrice);
        }
        return maxProfit;
    }
};
Best Time to Buy and Sell Stock in TypeScript
function maxProfit(prices: number[]): number {
    let minPrice = Infinity;
    let maxProfit = 0;
    for (const price of prices) {
        minPrice = Math.min(minPrice, price);
        maxProfit = Math.max(maxProfit, price - minPrice);
    }
    return maxProfit;
}
Best Time to Buy and Sell Stock in C
int maxProfit(int* prices, int pricesSize) {
    int minPrice = INT_MAX;
    int maxProfit = 0;
    for (int i = 0; i < pricesSize; i++) {
        if (prices[i] < minPrice) minPrice = prices[i];
        if (prices[i] - minPrice > maxProfit) maxProfit = prices[i] - minPrice;
    }
    return maxProfit;
}

More practice: DSA interview questions with answers · patterns cheat sheet

The approach, step by step

  1. Start with nothing

    Set the cheapest price seen to infinity and the best profit to 0.

  2. Lower the buy price

    For each day, keep the smaller of the cheapest price so far and today's price.

  3. Test selling today

    Compute today's price minus that cheapest price, keep it if it beats the best profit, and return the best at the end.

Frequently asked questions

Why is keeping only the cheapest price so far enough?

For a sale on any given day, the best buy day is simply the cheapest day before it: any other earlier day costs at least as much and so makes less. So the minimum seen so far is the only buy price worth remembering, and one pass suffices.


Why is this called a greedy algorithm?

At every day it commits to the locally best choices (the cheapest buy so far, and the best sale so far) and never revisits them. The greedy choice is provably safe here because a cheaper earlier buy can only ever improve a later sale.


What if the price only goes down?

Then no day is cheaper than a later one, every sale is measured against a minimum set that same day, and the best profit stays 0. The problem asks for 0 rather than a negative loss, which is why max_profit starts at 0.

New to the technique behind this problem? Watch it run step by step:

Greedy Algorithms Visualization

Applying for software engineering roles? Free, no sign-up:

AI resume checker: match your resume to the job description