What is the largest profit from at most one trade in a list of daily prices?

Coding
Easy
A Python puzzle about the best single trade in a list of daily prices.
Published

November 16, 2026

NoteQuestion

A stock’s daily closing prices are prices = [200, 204, 202, 206, 199, 203]. You may make at most one trade, buying one share at a close and selling it at a later close. Ignore trading costs. Write a short Python function that gives the largest profit.

Try it first, then open the solution.

The answer is 6, from buying at 200 and selling at 206. A function that reads the prices once gives it:

def best_single_trade(prices):
    low, best = prices[0], 0
    for price in prices:
        low = min(low, price)
        best = max(best, price - low)
    return best

Let \(P_t\) be the price on day \(t\) and \(L_t\) the lowest price up to and including day \(t\). Selling on day \(t\) earns at most \(P_t - L_t\), which is 0 when day \(t\) sets a new low, the profit of making no trade. The best profit is

\[\begin{aligned} \text{profit} &= \max_t\, (P_t - L_t), \\ L_t &= \min(P_0, \ldots, P_t). \end{aligned} \tag{1}\]

The loop keeps \(L_t\) in low and the largest \(P_t - L_t\) so far in best:

\(t\) \(P_t\) low, \(L_t\) \(P_t - L_t\) best
0 200 200 0 0
1 204 200 4 4
2 202 200 2 4
3 206 200 6 6
4 199 199 0 6
5 203 199 4 6

Three wrong answers are common:

Answer The slip
7 max(prices) - min(prices) sells at 206 before it buys at 199
4 the largest daily rise misses the trade from 200 to 206, which holds through the dip to 202
3 prices[-1] - prices[0] buys on the first day and sells on the last
def best_single_trade(prices):
    low, best = prices[0], 0
    for price in prices:
        low = min(low, price)
        best = max(best, price - low)
    return best


print(best_single_trade([200, 204, 202, 206, 199, 203]))
6