What is the largest profit from daily prices if you may trade as often as you like?
Coding
Medium
A Python puzzle about the largest trading profit from 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 start and finish with no shares, and you may buy or sell at any close as often as you like, holding at most one share at a time. Ignore trading costs. Write one line of Python that gives the largest total profit.
Try it first, then open the solution.
TipSolution
The answer is 12, and one line gives it:
profit =sum(max(today - yesterday, 0) for yesterday, today inzip(prices, prices[1:]))
Let \(P_t\) be the price on day \(t\), for \(t = 0, \ldots, 5\). A trade earns the sum of the daily changes while it holds the share. Buying at 200 and selling at 206, for example, earns \(4 - 2 + 4 = 6\). The largest total keeps every rise and skips every fall: