Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Program to find maximum profit we can get by buying and selling stocks with a fee in Python?
When trading stocks with transaction fees, we need to find the maximum profit possible by buying and selling stocks any number of times. Each sell transaction incurs a fee that reduces our profit.
The problem can be solved using dynamic programming with recursion. We track two states: whether we currently hold stock (flag=1) or not (flag=0).
Example
Let's say we have stock prices [2, 10, 4, 8] and a transaction fee of 3. The optimal strategy is:
- Buy at price 2, sell at price 10: profit = 10 - 2 - 3 = 5
- Buy at price 4, sell at price 8: profit = 8 - 4 - 3 = 1
- Total profit = 5 + 1 = 6
Recursive Solution
The algorithm uses a recursive function that considers two states at each price index ?
class Solution:
def solve(self, prices, fee):
n = len(prices)
def recur(i=0, flag=0):
# Base case: reached end of prices
if i == n:
return 0
# flag=0 means we don't hold stock (can buy)
if not flag:
# Option 1: Buy stock at current price
buy = recur(i + 1, 1) - prices[i]
# Option 2: Skip buying
skip = recur(i + 1, 0)
return max(buy, skip)
# flag=1 means we hold stock (can sell)
# Option 1: Hold stock (don't sell)
hold = recur(i + 1, 1)
# Option 2: Sell stock at current price (subtract fee)
sell = recur(i + 1, 0) + prices[i] - fee
return max(hold, sell)
return recur()
# Test the solution
ob = Solution()
prices = [2, 10, 4, 8]
fee = 3
print("Maximum profit:", ob.solve(prices, fee))
Maximum profit: 6
How It Works
The recursive function explores all possible buy/sell combinations:
- State 0 (no stock): We can either buy stock (transition to state 1) or skip
- State 1 (holding stock): We can either sell stock (transition to state 0 with fee) or hold
- The function returns the maximum profit from all possible decisions
Optimized Dynamic Programming Solution
For better performance with large inputs, we can use iterative dynamic programming ?
def max_profit_optimized(prices, fee):
# hold: maximum profit when holding stock
# sold: maximum profit when not holding stock
hold = -prices[0] # Buy first stock
sold = 0 # No stock initially
for i in range(1, len(prices)):
# Update hold: either keep current stock or buy new one
hold = max(hold, sold - prices[i])
# Update sold: either stay without stock or sell current stock
sold = max(sold, hold + prices[i] - fee)
return sold
# Test the optimized solution
prices = [2, 10, 4, 8]
fee = 3
print("Maximum profit (optimized):", max_profit_optimized(prices, fee))
Maximum profit (optimized): 6
Comparison
| Approach | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| Recursive | O(2^n) | O(n) | Understanding the logic |
| Dynamic Programming | O(n) | O(1) | Large datasets |
Conclusion
The stock trading problem with fees can be solved using dynamic programming by tracking buy/sell states. The recursive solution helps understand the logic, while the iterative approach provides optimal performance for large inputs.
