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
Stock Trading with Transaction FeeFind maximum profit with buy-sell transactions, each incurring a feeInputprices = [1, 3, 2, 8, 4, 9]fee = 2Each transaction costs 2 unitsOptimal StrategyBuy at 1, Sell at 8: profit = 5Buy at 4, Sell at 9: profit = 3Skip unprofitable tradesKey ChallengeTransaction fees reduce profitMust ensure: sell_price - buy_price > feeMaximum Profit: 8
Understanding the Visualization
1
Input
Array of stock prices over time and transaction fee
2
Process
Find optimal buy-sell sequence considering fees
3
Output
Maximum profit achievable after paying all fees
Key Takeaway
🎯 Key Insight: Track two states (holding vs cash) and ensure each transaction profit exceeds the fee
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