Best time to buy and sell stock

One pass, one buy and one sell: track the lowest price seen so far and the best profit it could unlock.

Time O(n)Space O(1)Code C#, Java, C++ and Python
Watch it animatedStep through it, with the running line highlighted. Free, no sign-in needed to watch.

The idea

You must buy before you sell, so walk the prices once remembering the lowest price seen so far. At every later day, check whether selling there would beat the best profit found yet; there is no need to track the actual buy day, only the running minimum.

Code

public static int MaxProfit(int[] prices) {
    int minPrice = prices[0], best = 0;
    for (int i = 1; i < prices.Length; i++) {
        if (prices[i] < minPrice) minPrice = prices[i];
        else best = Math.Max(best, prices[i] - minPrice);
    }
    return best;
}
static int maxProfit(int[] prices) {
    int minPrice = prices[0], best = 0;
    for (int i = 1; i < prices.length; i++) {
        if (prices[i] < minPrice) minPrice = prices[i];
        else best = Math.max(best, prices[i] - minPrice);
    }
    return best;
}
int maxProfit(const vector<int>& prices) {
    int minPrice = prices[0], best = 0;
    for (int i = 1; i < (int)prices.size(); i++) {
        if (prices[i] < minPrice) minPrice = prices[i];
        else best = max(best, prices[i] - minPrice);
    }
    return best;
}
def max_profit(prices: list[int]) -> int:
    min_price, best = prices[0], 0
    for i in range(1, len(prices)):
        if prices[i] < min_price: min_price = prices[i]
        else: best = max(best, prices[i] - min_price)
    return best

Tips

In the .NET library

Checking every buy-sell pair is O(n²); carrying just the running minimum forward turns it into one O(n) pass.