Command Palette

Search for a command to run...

Problem 32.2 · Advanced DPMedium

Best Time to Buy and Sell Stock with Transaction Fee

What it teaches: Two states, with the fee paid on each sale.

Practise it on judges as “Best Time to Buy and Sell Stock with Transaction Fee”.

The problem

Unlimited transactions, one share at a time, and each sale costs fee. Return the maximum profit.

Example 1

Input: prices = [1,3,2,8,4,9], fee = 2
Output: 8

Constraints

  • 1 ≤ n ≤ 5 × 10⁴

Pattern clues in the wording

  • → Per-transaction cost

These clues point to 1D Dynamic Programming: Define dp[i] as the answer for the first i items, write how it depends on smaller i, and fill it left to right.

Stuck? Take one hint at a time

Solution.java · starter
class Solution {
    public int maxProfit(int[] prices, int fee) {
        return 0;
    }
}

Write your solution locally or in your editor for now. The in-browser runner (Java first, then Python, C++ and more) will run these tests right here.

Test cases

#InputExpected
1
prices = [1,3,2,8,4,9]
fee = 2
8
2
prices = [1,3,7,5,10,3]
fee = 3
6

From slow to fast

Approaches

1

Two-state machine

Time O(n) Space O(1)

cash (no share) and hold (one share), updated each day.

Approach 1
class Solution {
    public int maxProfit(int[] prices, int fee) {
        int cash = 0, hold = -prices[0];
        for (int i = 1; i < prices.length; i++) {
            cash = Math.max(cash, hold + prices[i] - fee);
            hold = Math.max(hold, cash - prices[i]);
        }
        return cash;
    }
}

Verdict: Simple and optimal.

Before you submit

Edge cases and common mistakes

Test these inputs

  • Fee larger than any gain (0)
  • One day

Mistakes people make

  • Charging the fee on both buy and sell.

Interview

Follow-up questions

Why can hold use today's updated cash?