KatInterview

Stock Trading With a Per-Sale Commission

Dynamic ProgrammingAuto-graded · 23 test cases
MediumAuto-gradedDynamic Programmingdynamic-programmingstate-machinestocks

Last updated

Compute the best total gain from repeatedly buying and selling a single share of a stock when each sale costs a flat commission, using a two-state dynamic program.

You are given a list prices, where prices[i] is the cost of one share of a stock on day i, and a non-negative integer fee, a flat commission paid every time you sell a share.

You may trade as often as you like, under these rules:

  • You can own at most one share at any moment.
  • To buy again, you must first sell the share you currently own.
  • A buy and a sell each happen on a single day at that day's price. A day may include a sell followed by a buy.
  • The commission fee is paid once per completed trade (a buy followed by its sell). Buying costs nothing extra.
  • You are allowed to make no trades at all.

Return the largest total profit you can end up with, after all commissions are subtracted. A share bought but never sold does not count as a trade, and its purchase price is not recovered, so you should not end up with an unsold share if that lowers your profit.

If prices is empty, return 0.

Constraints

  • 0 <= len(prices) <= 5 * 10^4
  • 1 <= prices[i] <= 5 * 10^4
  • 0 <= fee <= 5 * 10^4
  • The result is never negative, since doing nothing yields 0.

Examples

Example 1

Input: best_profit_after_commission([1, 3, 2, 8, 4, 9], 2)

Output: 8

Example 2

Input: best_profit_after_commission([1, 3, 7, 5, 10, 3], 3)

Output: 6

Example 3

Input: best_profit_after_commission([1, 2, 3, 4, 5], 0)

Output: 4

Example 4

Input: best_profit_after_commission([7, 6, 4, 3, 1], 2)

Output: 0

Hints

Hint 1

On any given day you are in one of two situations: you hold a share or you do not. Think about the best profit you could have achieved for each situation.

Hint 2

Write the transitions. Not holding after today means you either were already not holding, or you sold today and paid the fee. Holding after today means you either were already holding, or you bought today using yesterday's not-holding profit.

Hint 3

Summing every positive daily rise fails once a fee exists, because each small rise would pay its own fee. Start with not-holding = 0 and holding = -prices[0], update both each day, and return the not-holding value at the end.