Python Scenario-Based Interview Question: Find Maximum Profit from Stock Prices
Python Scenario-Based Interview Question: Find Maximum Profit from Stock Prices
Python programming interviews often include scenario-based coding problems that test logical thinking and optimization skills. One of the most popular problems is calculating the maximum profit from stock prices by buying at one time and selling later.
Problem Scenario
You are given stock prices with timestamps:
prices = [
("2026-03-29 09:30:00", 150.25),
("2026-03-29 09:31:00", 152.10),
("2026-03-29 09:32:00", 151.80),
("2026-03-29 09:33:00", 154.50)
]
Question: Find the maximum profit by buying at one price and selling at a later higher price.
Expected Output:
4.25 # Buy at 150.25 (09:30), Sell at 154.50 (09:33)
๐ Python Code Solution
max_profit = 0
min_price = prices[0][1]
for time, price in prices[1:]:
profit = price - min_price
max_profit = max(max_profit, profit)
min_price = min(min_price, price)
print(f"{max_profit:.2f}")
Step-by-Step Explanation
1. Initialize Variables
- max_profit is set to 0
- min_price stores the lowest price seen so far
2. Loop Through Prices
We iterate through each price and calculate potential profit.
3. Calculate Profit
profit = price - min_price
4. Update Maximum Profit
max_profit = max(max_profit, profit)
5. Update Minimum Price
min_price = min(min_price, price)
Time and Space Complexity
| Complexity | Value |
|---|---|
| Time Complexity | O(n) |
| Space Complexity | O(1) |
Real-World Applications
- Stock market trading systems
- Financial analysis tools
- Cryptocurrency tracking
- Trading bots
- Investment software
Why Interviewers Ask This Question
- Tests problem-solving ability
- Checks algorithm optimization
- Evaluates logical thinking
- Measures coding efficiency
Example Walkthrough
| Time | Price | Min Price | Profit | Max Profit |
|---|---|---|---|---|
| 09:30 | 150.25 | 150.25 | 0 | 0 |
| 09:31 | 152.10 | 150.25 | 1.85 | 1.85 |
| 09:32 | 151.80 | 150.25 | 1.55 | 1.85 |
| 09:33 | 154.50 | 150.25 | 4.25 | 4.25 |
Alternative Python Function
def max_profit(prices):
max_profit = 0
min_price = prices[0][1]
for time, price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
return max_profit
print(max_profit(prices))
Edge Cases
- Prices always decreasing
- Only one price available
- Empty list
- Same price values
๐ Related Python Interview Questions
❓ Frequently Asked Questions (FAQ)
What is the time complexity of this algorithm?
The time complexity is O(n) because we iterate through the list once.
Can this problem be solved using Python?
Yes, Python provides simple loops and conditions to efficiently solve this problem.
Is this question asked in coding interviews?
Yes, it is a classic interview question known as "Best Time to Buy and Sell Stock".