↻one more pass.
Sliding window · Easy

Best Time to Buy and Sell Stock: the idea to remember.

Choose one earlier buy day and one later sell day to maximize profit, or return zero.

Solve on LeetCode ↗

The core insight

Keep the lowest price seen so far and evaluate each later selling price.

Why it works

The cheapest earlier buy is always the best partner for a fixed selling day. This is also a prefix minimum scan.

The mistake to avoid

A buy must precede a sell. Do not use a future minimum.

Time: O(n)Space: O(1)

Commented Java solution

Use java.util.* imports and a surrounding solution class. Tree snippets assume the standard TreeNode definition; linked lists use ListNode and Clone Graph uses a Node with val and neighbors; Copy Random List uses Node with val, next and random. Read the input assumptions above.

int maxProfit(int[] prices) {
    int cheapest = Integer.MAX_VALUE, best = 0;
    for (int price : prices) {
        cheapest = Math.min(cheapest, price);
        best = Math.max(best, price - cheapest);
    }
    return best;
}

Make the next connection

Independent revision notes with credited Java references. Not affiliated with LeetCode or the source sheets.