From Brute Force to Brilliance: Optimizing the Buy-Sell Stock Problem in Python
If you've ever worked with data structures and algorithms in Python, you've likely encountered the classic Buy-Sell Stock Problem.
As a software engineer working with algorithms daily, I've seen this problem surface in interviews, system design, and trading simulations.
Today, I will walk you through a real example of optimizing this algorithm from a naive brute-force solution to an efficient, clean, and production-ready version.
We'll proceed step-by-step, simplifying the logic and improving the performance—no fluff, just practical, high-quality Python.
Naive Solution: The Brute-Force Approach
Let's start with the original version. It's simple but inefficient.
# Brute-force version
def buy_sell(nums):
max_val = 0
for i in range(len(nums)):
start = nums[i]
new_list = nums[i + 1:]
end = check_max(new_list)
max_val = max(max_val, end - start)
return max_val
def check_max(nums):
max = 0
for i in nums:
if i > max:
max = i
return max
Why this is bad?:
- Inefficient: It loops the list multiple times, resulting in O(n^2) time complexity.
- Memory waste: new_list = nums[i + 1:] creates a new list in every iteration.
- Unscalable: With large datasets, this will choke.
Another Similar solution
def buy_sell(nums):
max_val=0
for i in range(len(nums)):
start=nums[i]
new_list=nums[i+1:]
end=max(new_list) if new_list else 0
max_val=max(max_val, end-start)
return max_val
The two solutions have the same time complexity despite the variation in implementation.
Optimal Solution: Linear Time, Constant Space
Now, here's the smarter way to do it: one pass, no slices, and no helper functions.
# Optimized version
def buy_sell(prices):
"""
Finds the maximum profit you can achieve from buying and selling one stock.
Parameters:
prices (List[int]): List of daily stock prices.
Returns:
int: Maximum achievable profit. 0 if no profit is possible.
"""
if not prices:
return 0
min_price = prices[0] # Track the lowest price seen so far
max_profit = 0 # Track the highest profit possible
for price in prices[1:]:
# Update the lowest price if current price is lower
min_price = min(min_price, price)
# Calculate profit if sold today
profit = price - min_price
# Update max profit if this is better
max_profit = max(max_profit, profit)
return max_profit
print(f"Expected: 5, Actual:", buy_sell([7,1,5,3,6,4]))
print(f"Expected: 0, Actual:",buy_sell([7,6,4,3,1]))
print(f"Expected: 0, Actual:",buy_sell([i for i in range(10**6, 0, -1)]))
print(f"Expected: 10**9 - 1, Actual:",buy_sell([1]*10**6 + [10**9]))
print(f"Expected: 999999 - 1 = 999998, Actual:",buy_sell(list(range(1, 10**6))))
What's Better Here?
- O(n) time complexity: Only one loop over the prices.
- O(1) space complexity: No extra lists, no helper functions.
- Cleaner logic: Easy to understand and maintain.
Diagram Explanation
Imagine walking through the prices from left to right. You're always looking for the lowest price to buy, and each day, you check if selling today gives you a better deal than before.
Bonus Tip: Want to Know When to Buy and Sell?
Here's a tweak to help you return not just the profit but also which day to buy and which day to sell:
# Return day indices too
def buy_sell_with_days(prices):
if not prices:
return 0, -1, -1
min_price = prices[0]
min_index = 0
max_profit = 0
buy_day = sell_day = 0
for i in range(1, len(prices)):
if prices[i] - min_price > max_profit:
max_profit = prices[i] - min_price
buy_day = min_index
sell_day = i
if prices[i] < min_price:
min_price = prices[i]
min_index = i
return max_profit, buy_day, sell_day
This is great for dashboards, visualizations, or trading logs.
What You Should Do Now
We just turned a slow, bulky function into a fast, scalable algorithm using basic Python techniques—no libraries, no magic. Whether you're prepping for interviews or building systems, these little upgrades matter.
Here's what you can do next:
- Refactor other brute-force loops in your projects using similar logic.
- Try visualizing the solution using charts for better intuition.
- Share this with someone learning Python—help them think about performance.
Want more Python tutorials like this? Bookmark PythonHaven.com and never stop improving!
Join the Discussion
No comments yet. Be the first to share your thoughts!