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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code