Best Time to Buy and Sell Stock with Transaction Fee

MediumDynamic programmingLeetCode 714 ↗World 5-6
0:00 / 0:00

Trade as often as you like, but every sale costs a fee. Track two states, cash and holding, and update both each day in one pass.

▼

The problem

LeetCode 714 (Medium). prices[i] is the price of a stock on day i and fee is charged once per completed transaction (a buy and its sell). Trade as many times as you like, holding at most one share at a time. Return the maximum profit. (Cousins in the series: ../best-time-to-buy-stock (one trade, the market monitor) and ../best-time-to-buy-and-sell-stock-with-cooldown (three states, the cottage); this one keeps its own river look.)

Example (LeetCode's first): prices = [1,3,2,8,4,9], fee = 2 → 8 (buy 1 sell 8: 7 − 2 = 5; buy 4 sell 9: 5 − 2 = 3; walked through in scene 6).

TRY IT ON LEETCODE ▶

The solution

def maxProfit(prices, fee):
    cash, hold = 0, -prices[0]
    for p in prices[1:]:
        cash = max(cash, hold + p - fee)
        hold = max(hold, cash - p)
    return cash

Transcript

Best Time to Buy and Sell Stock with Transaction Fee. Each day has a price. Trade as often as you like, holding one share at most, but every finished trade pays a fee. Find the most profit.

Take six days: one, three, two, eight, four, nine, with a fee of two. Buy at one, sell at eight: seven, minus the fee, five. Buy at four, sell at nine: three more. That's eight, the best you can do.

The naive way tries every plan: each day, trade or wait. That's two to the n paths: sixty-four for six days, over a billion for thirty.

The fee changes which trips pay. With no fee, you'd ride every rise: one to three, then two to eight. But a fee of two eats the first trip whole. One long trip, one to eight, nets five, beating the two short trips.

So keep two ledgers instead. Cash: the best profit holding nothing. Hold: the best profit owning a share. Each day, cash may sell: hold plus the price, minus the fee. Hold may buy: cash minus the price. Each keeps the larger.

Let's walk it. Cash starts at zero, hold at minus one. Price three: selling nets zero, so cash stays zero. Price two: nothing improves. Price eight: sell, and cash is five. Price four: buy back, and hold is one. Price nine: one plus nine, minus two: cash is eight.

In code: cash starts at zero, hold at minus the first price. For each later price, update cash, then hold. Hold may use today's new cash: selling and buying back the same day only pays a fee, so it never wins. Return cash.

One pass over the prices, and just two numbers: order n time, and constant space.

Two ledgers, one pass, one fee per trade. That's Best Time to Buy and Sell Stock with Transaction Fee.