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 the maximum profit we can get by buying on stock market once in Python
Finding the maximum profit from buying and selling stock once is a classic programming problem. Given a list of stock prices in chronological order, we need to find the maximum profit possible by buying once and selling once, where we must buy before selling.
For example, if the input is prices = [10, 12, 9, 6, 8, 12], the output will be 6, as we can buy at price 6 and sell at price 12.
Algorithm
To solve this efficiently, we use a single pass approach ?
- Initialize
max_profitto 0 - Initialize
min_priceto infinity - For each price in the list:
- Calculate profit if we sell at current price:
price - min_price - Update
max_profitif current profit is higher - Update
min_priceif current price is lower
- Calculate profit if we sell at current price:
- Return
max_profit
Implementation
def max_profit(prices):
max_profit = 0
min_price = float('inf')
for price in prices:
# Calculate profit if we sell at current price
max_profit = max(max_profit, price - min_price)
# Update minimum price seen so far
min_price = min(min_price, price)
return max_profit
# Test with example
prices = [10, 12, 9, 6, 8, 12]
result = max_profit(prices)
print(f"Maximum profit: {result}")
Maximum profit: 6
How It Works
Let's trace through the example [10, 12, 9, 6, 8, 12] ?
def max_profit_with_trace(prices):
max_profit = 0
min_price = float('inf')
print(f"{'Price':<6} {'Min Price':<10} {'Profit':<8} {'Max Profit':<12}")
print("-" * 40)
for price in prices:
current_profit = price - min_price if min_price != float('inf') else 0
max_profit = max(max_profit, current_profit)
min_price = min(min_price, price)
print(f"{price:<6} {min_price:<10} {current_profit:<8} {max_profit:<12}")
return max_profit
prices = [10, 12, 9, 6, 8, 12]
result = max_profit_with_trace(prices)
print(f"\nFinal maximum profit: {result}")
Price Min Price Profit Max Profit ---------------------------------------- 10 10 0 0 12 10 2 2 9 9 -1 2 6 6 -3 2 8 6 2 2 12 6 6 6 Final maximum profit: 6
Edge Cases
The algorithm handles various edge cases correctly ?
# Test edge cases
test_cases = [
([7, 1, 5, 3, 6, 4], 5), # Normal case
([7, 6, 4, 3, 1], 0), # Decreasing prices
([1, 2, 3, 4, 5], 4), # Increasing prices
([5], 0), # Single price
([], 0) # Empty list
]
def max_profit_safe(prices):
if len(prices) < 2:
return 0
max_profit = 0
min_price = float('inf')
for price in prices:
max_profit = max(max_profit, price - min_price)
min_price = min(min_price, price)
return max_profit
for prices, expected in test_cases:
result = max_profit_safe(prices)
print(f"Prices: {prices} ? Profit: {result} (Expected: {expected})")
Prices: [7, 1, 5, 3, 6, 4] ? Profit: 5 (Expected: 5) Prices: [7, 6, 4, 3, 1] ? Profit: 0 (Expected: 0) Prices: [1, 2, 3, 4, 5] ? Profit: 4 (Expected: 4) Prices: [5] ? Profit: 0 (Expected: 0) Prices: [] ? Profit: 0 (Expected: 0)
Time and Space Complexity
- Time Complexity: O(n) − single pass through the prices array
- Space Complexity: O(1) − only using constant extra space
Conclusion
This algorithm efficiently finds maximum stock profit in O(n) time by tracking the minimum price seen so far and calculating profit at each step. The key insight is that we only need to know the lowest price before the current day to determine the maximum profit possible.
