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.

The answer is 12, and one line gives it:

profit = sum(max(today - yesterday, 0) for yesterday, today in zip(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:

\[\text{profit} = \sum_{t=1}^{5} \max(P_t - P_{t-1},\, 0). \tag{1}\]

In the code, max(today - yesterday, 0) keeps a rise and turns a fall into 0, and sum adds the five results:

\(t\) yesterday today change kept by (1)
1 200 204 4 4
2 204 202 −2 0
3 202 206 4 4
4 206 199 −7 0
5 199 203 4 4

The kept changes sum to 12, from three trades: 200 to 204, 202 to 206 and 199 to 203.

Three wrong answers are common:

Answer The slip
7 max(prices) - min(prices) sells at 206 before it buys at 199
6 the best single trade, 200 to 206, uses one trade only
3 prices[-1] - prices[0] holds the share every day, through the falls too
prices = [200, 204, 202, 206, 199, 203]

profit = sum(max(today - yesterday, 0) for yesterday, today in zip(prices, prices[1:]))

print(profit)
12