Best Time to Buy and Sell Stock with Transaction Fee - Problem
You're a savvy day trader looking to maximize profits in the stock market! ๐
Given an array prices where prices[i] represents the stock price on day i, and a fee charged for each transaction, find the maximum profit you can achieve.
Trading Rules:
- You can complete unlimited transactions (buy and sell multiple times)
- You must sell before buying again (no simultaneous holdings)
- Each complete transaction (buy + sell) incurs a
fee - The fee is charged once per complete transaction
Goal: Determine the maximum profit possible after all trading fees are deducted.
Example: If prices = [1,3,2,8,4,9] and fee = 2, you could buy at 1, sell at 8 (profit: 8-1-2=5), then buy at 4, sell at 9 (profit: 9-4-2=3), for total profit of 8.
Input & Output
example_1.py โ Basic Case
$
Input:
prices = [1,3,2,8,4,9], fee = 2
โบ
Output:
8
๐ก Note:
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.py โ High Fees
$
Input:
prices = [1,3,7,5,10,3], fee = 3
โบ
Output:
6
๐ก Note:
Buy at price 1, sell at price 10 (profit: 10-1-3 = 6). Other transactions would not be profitable due to the high fee.
example_3.py โ No Profit Case
$
Input:
prices = [1,4,2], fee = 5
โบ
Output:
0
๐ก Note:
The transaction fee (5) is higher than any possible profit from buying and selling, so it's better not to trade at all.
Visualization
Tap to expand
Understanding the Visualization
1
Two States
Track maximum profit in two states: holding stock vs not holding stock
2
Daily Decisions
Each day, decide whether to buy, sell, or hold based on current price and fee
3
State Transitions
Update states: hold = max(keep holding, buy today), sold = max(stay sold, sell today - fee)
4
Optimal Result
Final answer is 'sold' state since we want to end without holding stock
Key Takeaway
๐ฏ Key Insight: Track two states (holding vs not holding) and transition optimally each day to maximize profit while accounting for transaction fees
Time & Space Complexity
Time Complexity
O(n)
Each state (day, holding) computed once, and there are 2n total states
โ Linear Growth
Space Complexity
O(n)
Memoization table plus recursion stack depth
โก Linearithmic Space
Constraints
- 1 โค prices.length โค 5 ร 104
- 1 โค prices[i] โค 5 ร 104
- 0 โค fee โค 5 ร 104
- All prices and fees are non-negative integers
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code