Best Time to Buy and Sell Stock with Transaction Fee - Problem

You are given an array prices where prices[i] is the price of a given stock on the i-th day, and an integer fee representing a transaction fee.

Find the maximum profit you can achieve. You may complete as many transactions as you like, but you need to pay the transaction fee for each transaction.

Note: You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). The transaction fee is only charged once for each stock purchase and sale.

Input & Output

Example 1 — Basic Case
$ Input: prices = [1, 3, 2, 8, 4, 9], fee = 2
Output: 8
💡 Note: Maximum profit is 8: buy at price 1, sell at price 8 (profit = 8-1-2 = 5), then buy at price 4, sell at price 9 (profit = 9-4-2 = 3). Total profit = 5 + 3 = 8.
Example 2 — High Transaction Fee
$ Input: prices = [1, 3, 7, 5, 10, 3], fee = 3
Output: 6
💡 Note: Best strategy: buy at 1, sell at 10 (profit = 10-1-3 = 6). Other transactions would be less profitable due to high fee.
Example 3 — No Profitable Transactions
$ Input: prices = [5, 4, 3, 2, 1], fee = 1
Output: 0
💡 Note: Prices are decreasing, so no profitable transactions are possible. Any buy-sell combination would result in loss.

Constraints

  • 1 ≤ prices.length ≤ 5 × 104
  • 1 ≤ prices[i] < 5 × 104
  • 0 ≤ fee < 5 × 104

Visualization

Tap to expand
Best Time to Buy and Sell Stock with Transaction Fee INPUT prices[] array 1 Day 0 3 Day 1 2 Day 2 8 Day 3 4 Day 4 9 Day 5 prices = [1, 3, 2, 8, 4, 9] fee = 2 Transaction fee per trade ALGORITHM STEPS 1 Initialize States hold = -prices[0], cash = 0 2 For Each Day Compare sell vs hold, buy vs wait 3 Update States cash = max(cash, hold+price-fee) hold = max(hold, cash-price) 4 Return Result Return cash (max profit) Greedy Transactions: BUY @1 --> SELL @8 +5 BUY @4 --> SELL @9 +3 Total: 5 + 3 = 8 FINAL RESULT Maximum Profit Calculation Transaction 1: Sell at 8 - Buy at 1 - Fee 2 = 5 Transaction 2: Sell at 9 - Buy at 4 - Fee 2 = 3 Total Profit: 5 + 3 = 8 Output: 8 OK - Verified! Optimal greedy strategy found Key Insight: The greedy approach tracks two states: holding stock (hold) and not holding (cash). At each step, we decide: keep current state OR switch (sell with fee / buy without fee). This ensures we only make profitable trades where gain exceeds the transaction fee. TutorialsPoint - Best Time to Buy and Sell Stock with Transaction Fee | Greedy Approach
Asked in
Facebook 15 Google 12 Amazon 18 Microsoft 10
125.0K Views
Medium Frequency
~25 min Avg. Time
4.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen