Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two states: holding and not holding.

Problem: Trade a stock any number of times (hold at most one share); each completed sale pays a fixed fee. Maximise profit with two states: holding and not holding.
def profit_fee(prices, fee):
    hold, cash = -prices[0], 0
    for p in prices[1:]:
        hold, cash = max(hold, cash - p), max(cash, hold + p - fee)
    return cash
pr = [2, 7, 5, 9, 3, 8]
print(profit_fee(pr, 2), profit_fee(pr, 4))
What is printed?
  1. A. 9 4
  2. B. 8 6
  3. C. 12 4
  4. D. 8 4

Correct answer: D. 8 4

hold = best value while owning a share, cash = best value with none. With fee 2: e.g. buy 2 / sell 9 (+5) then buy 3 / sell 8 (+3) → 8; trading every rise (+5, +4, +5 = 14 gross) pays three fees → 8 as well. With fee 4 only big swings pay: 2 → 9 (+3) and 3 → 8 (+1) → 4. Ignoring the fee gives 12 for the two swings. O(n), O(1).

More Coding Interview Problems questions

Exams that ask this topic