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.
TipSolution
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], 0for 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