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 after buying and selling stocks at most two times in python
Given a list of stock prices in chronological order, we need to find the maximum profit from buying and selling stocks at most two times. The constraint is that we must buy before selling, and we cannot hold multiple stocks simultaneously.
For example, if prices = [2, 6, 3, 4, 2, 9], the maximum profit is 11 by buying at 2, selling at 6 (profit: 4), then buying at 2 and selling at 9 (profit: 7).
Algorithm Approach
We use dynamic programming to track four states ?
- first_buy: Maximum profit after first purchase
- first_sell: Maximum profit after first sale
- second_buy: Maximum profit after second purchase
- second_sell: Maximum profit after second sale
Initially, all states are set to negative infinity since no transactions have occurred.
Implementation
def max_profit_two_transactions(prices):
if not prices or len(prices) < 2:
return 0
# Initialize all states to negative infinity
first_buy = first_sell = float("-inf")
second_buy = second_sell = float("-inf")
for price in prices:
# Update states in sequence
first_buy = max(first_buy, -price)
first_sell = max(first_sell, first_buy + price)
second_buy = max(second_buy, first_sell - price)
second_sell = max(second_sell, second_buy + price)
# Return maximum profit (could be 0 if no profitable transactions)
return max(0, first_sell, second_sell)
# Test the function
prices = [2, 6, 3, 4, 2, 9]
result = max_profit_two_transactions(prices)
print(f"Maximum profit: {result}")
Maximum profit: 11
How It Works
Let's trace through the algorithm with prices = [2, 6, 3, 4, 2, 9] ?
def max_profit_with_trace(prices):
first_buy = first_sell = float("-inf")
second_buy = second_sell = float("-inf")
print("Price | First_Buy | First_Sell | Second_Buy | Second_Sell")
print("-" * 60)
for price in prices:
first_buy = max(first_buy, -price)
first_sell = max(first_sell, first_buy + price)
second_buy = max(second_buy, first_sell - price)
second_sell = max(second_sell, second_buy + price)
print(f"{price:5} | {first_buy:9} | {first_sell:10} | {second_buy:10} | {second_sell:11}")
return max(0, first_sell, second_sell)
prices = [2, 6, 3, 4, 2, 9]
result = max_profit_with_trace(prices)
print(f"\nMaximum profit: {result}")
Price | First_Buy | First_Sell | Second_Buy | Second_Sell
------------------------------------------------------------
2 | -2 | 0 | -inf | -inf
6 | -2 | 4 | 4 | 4
3 | -2 | 4 | 4 | 7
4 | -2 | 4 | 4 | 8
2 | -2 | 4 | 4 | 8
9 | -2 | 4 | 4 | 11
Maximum profit: 11
Edge Cases
# Test edge cases
test_cases = [
[], # Empty list
[5], # Single price
[5, 4, 3, 2, 1], # Decreasing prices
[1, 2, 3, 4, 5], # Increasing prices
[3, 3, 3, 3] # Same prices
]
for i, prices in enumerate(test_cases):
profit = max_profit_two_transactions(prices)
print(f"Test {i+1}: {prices} ? Profit: {profit}")
Test 1: [] ? Profit: 0 Test 2: [5] ? Profit: 0 Test 3: [5, 4, 3, 2, 1] ? Profit: 0 Test 4: [1, 2, 3, 4, 5] ? Profit: 4 Test 5: [3, 3, 3, 3] ? Profit: 0
Time and Space Complexity
- Time Complexity: O(n) where n is the number of prices
- Space Complexity: O(1) as we use only four variables
Conclusion
This dynamic programming solution efficiently finds the maximum profit from at most two stock transactions in linear time. The key insight is tracking four states representing the profit at each transaction phase.
