Practice Lab

Best Time to Buy and Sell Stock

This is the single-transaction version of the stock profit problem. You can buy once and sell once, so every day asks one question: "If I sell today, what was the best earlier price to buy at?"

Problem

Given an array prices, where prices[i] is the stock price on day i, return the maximum profit from one buy and one sell.

Rules:

First Attempt

public int maxProfit(int[] prices) {
    var n = prices.length;
    var minPrice = prices[0];
    var maxProfit = 0;

    for (int i = 1; i < n; i++) {
        if (prices[i] < minPrice) {
            minPrice = prices[i];
        }

        var cp = prices[i] - minPrice;

        if (cp > maxProfit) {
            maxProfit = cp;
        }
    }

    return maxProfit;
}

This is already the right algorithm. It tracks:

The variable cp means current profit: selling today after buying at the best earlier price.

Clean Version

class Solution {
    public int maxProfit(int[] prices) {
        int minPrice = prices[0];
        int maxProfit = 0;

        for (int i = 1; i < prices.length; i++) {
            minPrice = Math.min(minPrice, prices[i]);
            maxProfit = Math.max(maxProfit, prices[i] - minPrice);
        }

        return maxProfit;
    }
}

Walkthrough

Input:

prices = [7, 1, 5, 3, 6, 4]

Steps:

daypricemin so farprofit if sold todaymax profit
07700
11100
25144
33124
46155
54135

Best trade:

buy at 1
sell at 6
profit = 5

Why This Works

At each day, we only need the cheapest price before or at that day.

If today's price is lower than minPrice, it becomes the new best buy candidate.

If today's price is higher, selling today gives:

prices[i] - minPrice

We keep the maximum of those candidate profits.

Stock I vs Stock II

ProblemTransactionsPattern
Best Time to Buy and Sell StockOne buy and one sellTrack minimum so far
Best Time to Buy and Sell Stock IIUnlimited transactionsSum every positive daily gain

The first problem needs one best global trade.

The second problem collects every profitable rise.

Edge Cases

[7, 6, 4, 3, 1] -> 0
[7, 1, 5, 3, 6, 4] -> 5
[1, 2] -> 1
[2, 1] -> 0

For the usual LeetCode constraints, prices.length >= 1. If that is not guaranteed, add:

if (prices == null || prices.length == 0) {
    return 0;
}

Complexity

ApproachTimeSpace
Track minimum so farO(n)O(1)

Takeaways