KatInterview

Stock Trading Profit with Transaction Limits and Fees

Dynamic ProgrammingModel answer
MediumModel answerDynamic Programmingdynamic-programmingstate-machinegreedy

Last updated

Maximize stock trading profit given a cap on total transactions and a per-sale fee, using a unified DP state machine.

Stock Trading Profit with Transaction Limits and Fees

You are building a profit calculator for a trading platform that enforces two constraints: a cap on how many trades a user can make, and a flat fee charged every time they sell.

Given a list of daily prices prices, an integer k (maximum number of buy/sell pairs allowed), and a number fee (cost deducted at the time of each sale), return the maximum total profit achievable.

def max_profit(prices: list[int], k: int, fee: float) -> float:
    pass

Rules

  1. You may complete at most k transactions. One transaction = one buy followed by one sell.
  2. You must sell your current share before buying again (no overlapping positions).
  3. The fee is charged once per transaction, at the moment of sale.
  4. Holding and doing nothing is always allowed — you are never forced to trade.

Constraints

  • 1 <= len(prices) <= 10^4
  • 0 <= prices[i] <= 10^5
  • 0 <= k <= 10^9
  • 0 <= fee <= 10^5

Examples

Example 1

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

Buy on day 0 (price 1), sell on day 3 (price 8): profit = 7 − 2 = 5.
Buy on day 4 (price 4), sell on day 5 (price 9): profit = 5 − 2 = 3.
Total = 8.0.

Example 2

prices = [1, 2], k = 1000000000, fee = 0
Output: 1.0

No fee, effectively unlimited trades; only one profitable move exists.

What is expected

  • A correct implementation that handles all constraint ranges, including k up to 10^9.
  • A brief explanation of your approach, why naive greedy fails when fee > 0, and the time and space complexity of your solution.

Hints

Hint 1

At most ⌊n/2⌋ transactions can ever be profitable in n days (each needs a distinct buy day before its sell day). If k is larger than that, the cap never actually binds — treat it as unlimited trades and solve with two scalars instead of a huge array.

Hint 2

Model each day as a state machine with two states: 'free' (no stock held, tracks max cash after j completed sales) and 'holding' (own one share, tracks max cash while in the j-th open trade). The transitions are: open a position by subtracting today's price from the free state, close it by adding today's price and subtracting the fee.

Hint 3

Greedy 'sum every upswing' stops working the moment fee > 0, because merging two adjacent up-moves into one transaction saves a fee. The DP captures this automatically — you don't need to special-case it.