Buy and Sell Stocks All Variants in DSA C - Time & Space Complexity
When solving buy and sell stock problems, we want to know how the time needed changes as the number of days grows.
We ask: How does the number of price checks and decisions grow with more days?
Analyze the time complexity of the following code snippet.
int maxProfit(int* prices, int pricesSize) {
int minPrice = prices[0];
int maxProfit = 0;
for (int i = 1; i < pricesSize; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
This code finds the best single buy and sell day to maximize profit from stock prices over days.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop that goes through the price list once.
- How many times: Exactly once for each day after the first.
As the number of days increases, the code checks each day's price once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 9 checks |
| 100 | About 99 checks |
| 1000 | About 999 checks |
Pattern observation: The number of operations grows 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 buy and sell days is needed to find max profit."
[OK] Correct: This would take much longer, but the smart one-pass method finds the answer by remembering the lowest price so far.
Understanding how to scan prices once and keep track of key values shows you can write efficient code, a skill interviewers appreciate.
"What if we allowed multiple buy and sell transactions? How would the time complexity change?"
Practice
Buy and Sell Stocks problem variants?Solution
Step 1: Understand the problem objective
The problem asks to maximize profit by buying and selling stocks on certain days.Step 2: Identify the key action
Choosing the best days to buy low and sell high maximizes profit.Final Answer:
Maximize the profit by choosing the best days to buy and sell stocks -> Option AQuick Check:
Goal = Maximize profit [OK]
- Confusing profit maximization with minimizing transactions
- Ignoring the selling day after buying
- Thinking only about highest price day
Solution
Step 1: Check variable initialization syntax
In C, integer variables are initialized with integer values, zero is valid.Step 2: Validate each option
int maxProfit = 0; uses int maxProfit = 0; which is correct. int maxProfit = -1; uses -1 which is valid but not typical for profit initialization. int maxProfit = NULL; uses NULL which is for pointers, not int. int maxProfit = '0'; uses character '0' which is ASCII 48, not zero.Final Answer:
int maxProfit = 0; -> Option AQuick Check:
Correct int initialization = int maxProfit = 0; [OK]
- Using NULL for integer variables
- Initializing with character '0' instead of number 0
- Starting profit with negative values unnecessarily
int prices[] = {7, 1, 5, 3, 6, 4};
int maxProfit = 0, minPrice = prices[0];
for (int i = 1; i < 6; i++) {
if (prices[i] < minPrice) minPrice = prices[i];
else if (prices[i] - minPrice > maxProfit) maxProfit = prices[i] - minPrice;
}
printf("%d", maxProfit);Solution
Step 1: Trace the loop to find minPrice and maxProfit
Start minPrice=7, maxProfit=0. Iterations:
i=1: price=1 < 7, minPrice=1
i=2: price=5, profit=5-1=4 > 0, maxProfit=4
i=3: price=3, profit=3-1=2 < 4, no change
i=4: price=6, profit=6-1=5 > 4, maxProfit=5
i=5: price=4, profit=4-1=3 < 5, no changeStep 2: Final maxProfit after loop
maxProfit is 5 after all iterations.Final Answer:
5 -> Option BQuick Check:
Max profit = 5 [OK]
- Not updating minPrice correctly
- Calculating profit before updating minPrice
- Confusing maxProfit with max price
int maxProfit = 0;
int prices[] = {1, 2, 3, 4, 5};
for (int i = 0; i < 5; i++) {
if (prices[i] > prices[i-1]) {
maxProfit += prices[i] - prices[i-1];
}
}
printf("%d", maxProfit);Solution
Step 1: Analyze loop index usage
The loop starts at i=0, so prices[i-1] is prices[-1], which is invalid memory access.Step 2: Correct the loop start
Loop should start at i=1 to safely access prices[i-1].Final Answer:
Loop starts at i=0 causing out-of-bounds access at prices[i-1] -> Option CQuick Check:
Index error at i=0 [OK]
- Starting loop at 0 when accessing i-1
- Incorrect comparison operator in if condition
- Ignoring array bounds
{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 profit.Step 2: Calculate max profit for two transactions
First transaction: buy at 3 (day 0), sell at 5 (day 2), profit = 2.
Second transaction: buy at 0 (day 3), sell at 4 (day 7), profit = 4.
Total profit = 2 + 4 = 6.Step 3: Check for better transactions
Alternatively, buy at 0 (day 3), sell at 3 (day 5), profit = 3.
Then buy at 1 (day 6), sell at 4 (day 7), profit = 3.
Total profit = 3 + 3 = 6.
But better is buy at 0 (day 3), sell at 5 (day 2) is invalid (sell before buy). So best is 6 or 7 or 8?
Actually, the maximum profit with two transactions is 7:
Buy at 0 (day 3), sell at 3 (day 5), profit = 3.
Buy at 1 (day 6), sell at 4 (day 7), profit = 3.
Total profit = 6.
But if we consider buy at 3 (day 0), sell at 5 (day 2), profit = 2.
Buy at 0 (day 3), sell at 4 (day 7), profit = 4.
Total profit = 6.
However, the maximum profit is 7:
Buy at 0 (day 3), sell at 5 (day 2) invalid.
Buy at 0 (day 3), sell at 4 (day 7), profit = 4.
Buy at 1 (day 6), sell at 4 (day 7), profit = 3.
Total profit = 7.
So the correct maximum profit is 7.Final Answer:
7 -> Option DQuick Check:
Two transactions max profit = 7 [OK]
- Counting overlapping transactions
- Ignoring zero price days
- Assuming unlimited transactions
Ready to prove it?
Pass the test and this pattern moves unknown
