What is the largest profit from daily prices with at most two trades?

Coding
Hard
A Python puzzle about the best two trades 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 two trades, each a buy followed later by a sell, and you can hold at most one share at a time. Ignore trading costs. Write a short Python function that gives the largest total profit.

Try it first, then open the solution.

The answer is 10, from buying at 200 and selling at 206, then buying at 199 and selling at 203. A function that tries every split day 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


def best_two_trades(prices):
    best = 0
    for k in range(len(prices)):
        first_profit = best_single_trade(prices[:k + 1])
        second_profit = best_single_trade(prices[k:])
        best = max(best, first_profit + second_profit)
    return best

Two trades that do not overlap have a split day \(k\) between the first sell and the second buy. Let \(B(i, j)\) be the largest profit from at most one trade between day \(i\) and day \(j\), with 0 for no trade. Both ranges include day \(k\), which allows a sell and a buy at the same close, so the largest total profit is

\[\text{profit} = \max_k\, \big[ B(0, k) + B(k, 5) \big]. \tag{1}\]

For each split day \(k\) from 0 to 5, the loop computes first_profit over days 0 to \(k\) with prices[:k + 1] and second_profit over days \(k\) to 5 with prices[k:], both with best_single_trade from the one-trade quiz, and keeps the largest sum in best:

\(k\) first_profit, \(B(0, k)\) second_profit, \(B(k, 5)\) sum
0 0 6 6
1 4 4 8
2 4 4 8
3 6 4 10
4 6 4 10
5 6 0 6

Each split day rescans the prices, so the work grows with the square of the number of days, which is fine for six days.

Three wrong answers are common:

Answer The slip
12 sums every rise, which takes three trades
8 adds the two largest daily rises, 4 + 4, and misses the trade from 200 to 206 through the dip
6 stops after the best single trade, 200 to 206
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


def best_two_trades(prices):
    best = 0
    for k in range(len(prices)):
        first_profit = best_single_trade(prices[:k + 1])
        second_profit = best_single_trade(prices[k:])
        best = max(best, first_profit + second_profit)
    return best


print(best_two_trades([200, 204, 202, 206, 199, 203]))
10