Bird
Raised Fist0
DSA C#programming~10 mins

Buy and Sell Stocks All Variants in DSA C# - Execution Trace

Choose your learning style10 modes available
Concept Flow - Buy and Sell Stocks All Variants
Start
↓
Initialize variables: minPrice, maxProfit
↓
Iterate over prices
↓
Compare current price with minPrice
↓
Calculate profit = current price - minPrice
↓
Continue iteration
↓
Return maxProfit
↓
End
The flow shows how we track the lowest price and calculate the maximum profit by iterating through stock prices once.
Execution Sample
DSA C#
int maxProfit = 0;
int minPrice = prices[0];
for (int i = 1; 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 one buy and one sell by tracking the minimum price and updating max profit.
Execution Table
StepOperationCurrent PriceminPricemaxProfitProfit CalculationVisual State
1Initializeprices[0]=770-[7]
2Check price=1 < minPrice=7110-[7 -> 1]
3Calculate profit=1-1=0 > maxProfit=0?1100[7 -> 1]
4Check price=5 < minPrice=1510-[7 -> 1 -> 5]
5Calculate profit=5-1=4 > maxProfit=0?5144[7 -> 1 -> 5]
6Check price=3 < minPrice=1314-[7 -> 1 -> 5 -> 3]
7Calculate profit=3-1=2 > maxProfit=4?3142[7 -> 1 -> 5 -> 3]
8Check price=6 < minPrice=1614-[7 -> 1 -> 5 -> 3 -> 6]
9Calculate profit=6-1=5 > maxProfit=4?6155[7 -> 1 -> 5 -> 3 -> 6]
10Check price=4 < minPrice=1415-[7 -> 1 -> 5 -> 3 -> 6 -> 4]
11Calculate profit=4-1=3 > maxProfit=5?4153[7 -> 1 -> 5 -> 3 -> 6 -> 4]
12End iteration-15-[7 -> 1 -> 5 -> 3 -> 6 -> 4]
💡 Iteration ends after last price; maxProfit=5 is returned.
Variable Tracker
VariableStartAfter Step 2After Step 5After Step 9Final
minPrice71111
maxProfit00455
Current Price71564
Key Moments - 3 Insights
Why do we update minPrice only when current price is less?
Because minPrice tracks the lowest price to buy. Updating it only when a lower price appears ensures we buy at the cheapest price before selling. See execution_table steps 2 and 5.
Why do we calculate profit only if current price is not less than minPrice?
Calculating profit when current price is less than minPrice would be negative or zero profit. We only calculate profit when selling price is higher than buying price. See execution_table steps 3, 5, 7, 9.
Why does maxProfit update only when new profit is greater?
Because we want the maximum profit possible. Updating maxProfit only when new profit is higher ensures we keep the best profit found so far. See execution_table steps 5 and 9.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at step 5, what is the maxProfit value?
A0
B5
C4
D1
💡 Hint
Check the maxProfit column at step 5 in execution_table.
At which step does minPrice first update to 1?
AStep 1
BStep 2
CStep 4
DStep 9
💡 Hint
Look at minPrice changes in variable_tracker and execution_table step 2.
If the prices array was strictly decreasing, what would maxProfit be at the end?
A0
BNegative value
CFirst price value
DLast price value
💡 Hint
Recall maxProfit updates only when profit is positive; see key_moments about profit calculation.
Concept Snapshot
Buy and Sell Stocks (One Transaction):
- Track minPrice (lowest buy price) while iterating prices
- Calculate profit = current price - minPrice
- Update maxProfit if profit is higher
- Return maxProfit after iteration
- Time: O(n), Space: O(1)
Full Transcript
This concept shows how to find the maximum profit from buying and selling a stock once. We start by setting minPrice to the first price and maxProfit to zero. Then, for each price, if it is lower than minPrice, we update minPrice. Otherwise, we calculate the profit by subtracting minPrice from the current price. If this profit is greater than maxProfit, we update maxProfit. After checking all prices, we return maxProfit. This ensures we buy at the lowest price before selling at a higher price to maximize profit.

Practice

(1/5)
1. What is the main goal when solving the Buy and Sell Stocks problem variants?
easy
A. Minimize the number of transactions regardless of profit
B. Find the stock price on the last day only
C. Maximize the profit by choosing the best days to buy and sell stocks
D. Calculate the average stock price over all days

Solution

  1. Step 1: Understand the problem objective

    The problem asks to maximize profit by buying and selling stocks on certain days.
  2. Step 2: Identify the key action

    Choosing the best days to buy low and sell high maximizes profit.
  3. Final Answer:

    Maximize the profit by choosing the best days to buy and sell stocks -> Option C
  4. Quick Check:

    Goal = Maximize profit [OK]
Hint: Focus on profit maximization, not just transactions [OK]
Common Mistakes:
  • Confusing profit with number of transactions
  • Ignoring the buy before sell rule
  • Trying to find average price instead of max profit
2. Which of the following C# code snippets correctly initializes an array of stock prices for the Buy and Sell Stocks problem?
easy
A. int prices[] = new int[6] {7, 1, 5, 3, 6, 4};
B. int prices = {7, 1, 5, 3, 6, 4};
C. int[] prices = (7, 1, 5, 3, 6, 4);
D. int[] prices = new int[] {7, 1, 5, 3, 6, 4};

Solution

  1. Step 1: Check correct array initialization syntax in C#

    In C#, arrays are initialized with int[] prices = new int[] { ... };.
  2. 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.
  3. Final Answer:

    int[] prices = new int[] {7, 1, 5, 3, 6, 4}; -> Option D
  4. Quick Check:

    Correct C# array syntax = int[] prices = new int[] {7, 1, 5, 3, 6, 4}; [OK]
Hint: Use int[] arr = new int[] { ... }; for arrays [OK]
Common Mistakes:
  • Omitting 'new int[]' when initializing arrays
  • Using parentheses instead of braces
  • Declaring arrays like in C or Java incorrectly
3. What is the output of the following C# code that finds the maximum profit with only one transaction allowed?
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);
medium
A. 6
B. 5
C. 4
D. 7

Solution

  1. 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.
  2. Step 2: Identify final max profit

    Max profit is 5, achieved by buying at 1 and selling at 6.
  3. Final Answer:

    5 -> Option B
  4. Quick Check:

    Max profit one transaction = 5 [OK]
Hint: Track min price and update max profit on each day [OK]
Common Mistakes:
  • Confusing max profit with max price
  • Not updating min price correctly
  • Calculating profit without checking min price
4. The following code is intended to calculate the maximum profit with unlimited transactions allowed. What is the bug?
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;
medium
A. There is no bug; code works correctly
B. The code does not handle empty price array
C. The loop should start from i = 0
D. The code incorrectly adds profit when prices decrease

Solution

  1. 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.
  2. 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.
  3. Final Answer:

    There is no bug; code works correctly -> Option A
  4. Quick Check:

    Unlimited transactions profit logic = correct [OK]
Hint: Add profit only when price increases day-to-day [OK]
Common Mistakes:
  • Starting loop at wrong index
  • Adding profit on price drops
  • Ignoring empty or single-element arrays
5. Given the prices array {3, 3, 5, 0, 0, 3, 1, 4} and a limit of at most two transactions, what is the maximum profit achievable?
hard
A. 8
B. 7
C. 5
D. 6

Solution

  1. Step 1: Understand the two transactions limit

    We can buy and sell at most twice to maximize profit.
  2. 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).
  3. Final Answer:

    8 -> Option A
  4. Quick Check:

    Two transactions max profit = 8 [OK]
Hint: Split array to find best two transaction profits [OK]
Common Mistakes:
  • Counting more than two transactions
  • Not choosing optimal buy/sell days
  • Adding profits incorrectly
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard