Buy and Sell Stocks All Variants in DSA Python - Time & Space Complexity
When solving buy and sell stock problems, we want to know how the time needed grows as the number of days increases.
We ask: How does the number of price checks and decisions change when we have more days?
Analyze the time complexity of the following code snippet.
prices = [7,1,5,3,6,4]
max_profit = 0
min_price = float('inf')
for price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
print(max_profit)
This code finds the best profit from buying and selling once by scanning prices once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop through the list of prices.
- How many times: Exactly once for each day (n times).
As the number of days grows, the code checks each price once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The operations grow directly with the number of days.
Time Complexity: O(n)
This means the time needed grows in a straight line with the number of days.
[X] Wrong: "Checking every pair of days is needed to find max profit."
[OK] Correct: We can find max profit by one pass, tracking the lowest price and best profit so far, without checking all pairs.
Understanding how to scan prices efficiently shows you can find smart solutions that save time, a skill valued in real coding tasks.
"What if we could buy and sell multiple times? How would the time complexity change?"
Practice
Buy and Sell Stocks problem variants?Solution
Step 1: Understand the problem goal
The problem asks to find the best days to buy and sell stocks to get the highest profit.Step 2: Identify the objective
Maximizing profit means buying low and selling high at the right times.Final Answer:
Maximize the profit by choosing the best days to buy and sell stocks -> Option CQuick Check:
Goal = Maximize profit [OK]
- Thinking the goal is to minimize transactions
- Only finding lowest price day without selling
- Calculating averages instead of profit
Solution
Step 1: Understand initialization needs
We want min_price to start very high so any price is lower, and max_profit to start at zero.Step 2: Check each option
min_price = float('inf'); max_profit = 0 sets min_price to infinity and max_profit to zero, which is correct for tracking minimum and maximum values.Final Answer:
min_price = float('inf'); max_profit = 0 -> Option AQuick Check:
Initialization = min_price high, max_profit zero [OK]
- Setting min_price to zero causes wrong minimum tracking
- Using None without checks causes errors
- Setting max_profit to negative infinity can confuse logic
min_price = float('inf')
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
print(max_profit)Solution
Step 1: Trace the loop with given prices
Prices: 7,1,5,3,6,4 - Start min_price=inf, max_profit=0 - price=7: min_price=7 - price=1: min_price=1 (lower) - price=5: profit=5-1=4 > 0, max_profit=4 - price=3: profit=3-1=2 < 4, no change - price=6: profit=6-1=5 > 4, max_profit=5 - price=4: profit=4-1=3 < 5, no changeStep 2: Final max_profit after loop
max_profit is 5 after checking all prices.Final Answer:
5 -> Option DQuick Check:
Max profit = 5 [OK]
- Confusing max profit with max price
- Not updating min_price correctly
- Calculating profit incorrectly
prices = [7,1,5,3,6,4]
min_price = 0
max_profit = 0
for price in prices:
if price < min_price:
min_price = price
elif price - min_price > max_profit:
max_profit = price - min_price
print(max_profit)Solution
Step 1: Check variable initialization
min_price is set to 0, but prices include values greater than 0, so min_price never updates to actual minimum (1).Step 2: Effect of wrong min_price initialization
Since min_price=0, price < min_price is never true, so min_price stays 0, causing incorrect profit calculations.Final Answer:
min_price initialized to 0 instead of a high value -> Option BQuick Check:
min_price must start high to track minimum [OK]
- Starting min_price at zero causes wrong minimum tracking
- Confusing max_profit initialization
- Thinking elif causes logic error here
[3,3,5,0,0,3,1,4], what is the maximum profit with at most two transactions?Solution
Step 1: Understand two transactions limit
We can buy and sell stocks at most twice to maximize total profit.Step 2: Calculate profits for two transactions
First transaction: buy at 3, sell at 5 = 2 profit Second transaction: buy at 0, sell at 4 = 4 profit Total profit = 2 + 4 = 6Final Answer:
6 -> Option AQuick Check:
Two transactions max profit = 6 [OK]
- Counting overlapping transactions
- Only considering one transaction
- Adding profits incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
