Problem 307698 · medium · Phase 03 Linear Management & Searching

Trading With a Commission

greedy · state machine · dynamic programming

prices[i] is the price of a crate of tea on day i. You may buy and sell as often as you like, holding at most one crate at a time, but every sale costs a fixed commission fee. Return the largest total profit you can finish with. If no trade is worthwhile, return 0.

Examples

Input:  prices = [1, 4, 6, 2, 8], fee = 2
Output: 7
Explanation: Buy at 1, sell at 6 (6 - 1 - 2 = 3); buy at 2, sell at 8 (8 - 2 - 2 = 4).
Input:  prices = [5, 4, 3], fee = 1
Output: 0

Constraints

  • 1 <= len(prices) <= 5 * 10**4, 1 <= prices[i] <= 10**5, 0 <= fee <= 10**5.
  • Target complexity: O(n) time, O(1) extra space.

Goals

  • Model the trader as two states: holding a crate or holding cash
  • Charge the commission at exactly one point of each trade
Starting Python…