Buy and Sell Stocks All Variants in DSA C# - Time & Space Complexity
We want to understand how the time needed to find the best buy and sell days grows as the number of stock prices increases.
How does the number of prices affect the work our code must do?
Analyze the time complexity of the following code snippet.
public int MaxProfit(int[] prices) {
int minPrice = int.MaxValue;
int maxProfit = 0;
for (int i = 0; i < prices.Length; i++) {
if (prices[i] < minPrice) {
minPrice = prices[i];
} else if (prices[i] - minPrice > maxProfit) {
maxProfit = prices[i] - minPrice;
}
}
return maxProfit;
}
This code finds the maximum profit from buying and selling a stock once by scanning prices once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single loop through the prices array.
- How many times: Exactly once for each price, so n times if there are n prices.
As the number of prices grows, the code checks each price once, so the work grows directly with the number of prices.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The work grows in a straight line with input size.
Time Complexity: O(n)
This means the time to find the best buy and sell days grows directly with the number of prices.
[X] Wrong: "We must check every pair of days, so the time is always n squared."
[OK] Correct: This code smartly tracks the lowest price so far and calculates profit in one pass, avoiding checking all pairs.
Understanding this time complexity shows you can find efficient solutions by scanning data once, a key skill in many coding challenges.
"What if we wanted to find the maximum profit with unlimited 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 CQuick Check:
Goal = Maximize profit [OK]
- Confusing profit with number of transactions
- Ignoring the buy before sell rule
- Trying to find average price instead of max profit
Solution
Step 1: Check correct array initialization syntax in C#
In C#, arrays are initialized withint[] prices = new int[] { ... };.Step 2: Verify each option
int[] prices = new int[] {7, 1, 5, 3, 6, 4};uses correct syntax. The other options have invalid syntax: one declares a single int without array type, another uses parentheses instead of braces, and the last has incorrect array declaration style.Final Answer:
int[] prices = new int[] {7, 1, 5, 3, 6, 4}; -> Option DQuick Check:
Correct C# array syntax = int[] prices = new int[] {7, 1, 5, 3, 6, 4}; [OK]
int[] arr = new int[] { ... }; for arrays [OK]- Omitting 'new int[]' when initializing arrays
- Using parentheses instead of braces
- Declaring arrays like in C or Java incorrectly
int[] prices = {7, 1, 5, 3, 6, 4};
int minPrice = int.MaxValue;
int maxProfit = 0;
foreach (int price in prices) {
if (price < minPrice) minPrice = price;
else if (price - minPrice > maxProfit) maxProfit = price - minPrice;
}
Console.WriteLine(maxProfit);Solution
Step 1: Trace the minimum price and max profit updates
Prices: 7,1,5,3,6,4. Min price updates to 7 then 1. Max profit updates when price - minPrice > maxProfit: 5-1=4, 6-1=5.Step 2: Identify final max profit
Max profit is 5, achieved by buying at 1 and selling at 6.Final Answer:
5 -> Option BQuick Check:
Max profit one transaction = 5 [OK]
- Confusing max profit with max price
- Not updating min price correctly
- Calculating profit without checking min price
int maxProfit = 0;
for (int i = 1; i < prices.Length; i++) {
if (prices[i] > prices[i - 1]) {
maxProfit += prices[i] - prices[i - 1];
}
}
return maxProfit;Solution
Step 1: Understand the logic for unlimited transactions
The code adds profit for every increase from day i-1 to i, which is correct for unlimited transactions.Step 2: Check for bugs
The loop starts at 1 to compare with previous day. It skips empty array handling but not asked here. No incorrect profit addition.Final Answer:
There is no bug; code works correctly -> Option AQuick Check:
Unlimited transactions profit logic = correct [OK]
- Starting loop at wrong index
- Adding profit on price drops
- Ignoring empty or single-element arrays
{3, 3, 5, 0, 0, 3, 1, 4} and a limit of at most two transactions, what is the maximum profit achievable?Solution
Step 1: Understand the two transactions limit
We can buy and sell at most twice to maximize profit.Step 2: Calculate max profit by splitting days
First transaction: buy at 3, sell at 5 (profit 2). Second transaction: buy at 0, sell at 4 (profit 4). Total profit = 2 + 4 = 6. But better transactions are buy at 0 sell at 3 (profit 3), then buy at 1 sell at 4 (profit 3), total 6. However, the maximum profit is actually 8 by buying at 0 and selling at 5 (profit 5), then buying at 1 and selling at 4 (profit 3).Final Answer:
8 -> Option AQuick Check:
Two transactions max profit = 8 [OK]
- Counting more than two transactions
- Not choosing optimal buy/sell days
- Adding profits incorrectly
Ready to prove it?
Pass the test and this pattern moves unknown
