Bird
Raised Fist0
DSA C#programming

Buy and Sell Stocks All Variants in DSA C#

Choose your learning style10 modes available
Mental Model
We want to find the best times to buy and sell stocks to maximize profit by looking at price changes over days.
Analogy: Imagine you are a fruit seller buying fruits at low prices and selling them later at higher prices to earn money, but you can only hold one fruit at a time or multiple depending on the variant.
Day:    0    1    2    3    4    5
Price:  7 ->  1 ->  5 ->  3 ->  6 ->  4
Buy?   ↑
Sell?        ↑
Dry Run Walkthrough
Input: prices = [7, 1, 5, 3, 6, 4], variant = 'single transaction'
Goal: Find the maximum profit by buying once and selling once later
Step 1: Set min_price to 7 (price at day 0), max_profit to 0
Day: 0 -> Price: 7 [min_price=7, max_profit=0]
Why: We start tracking the lowest price to buy
Step 2: At day 1, price is 1, update min_price to 1 because 1 < 7
Day: 1 -> Price: 1 [min_price=1, max_profit=0]
Why: We found a cheaper price to buy
Step 3: At day 2, price is 5, calculate profit = 5 - 1 = 4, update max_profit to 4
Day: 2 -> Price: 5 [min_price=1, max_profit=4]
Why: Selling now yields better profit
Step 4: At day 3, price is 3, profit = 3 - 1 = 2, max_profit stays 4
Day: 3 -> Price: 3 [min_price=1, max_profit=4]
Why: Profit less than max_profit, no update
Step 5: At day 4, price is 6, profit = 6 - 1 = 5, update max_profit to 5
Day: 4 -> Price: 6 [min_price=1, max_profit=5]
Why: Better profit found
Step 6: At day 5, price is 4, profit = 4 - 1 = 3, max_profit stays 5
Day: 5 -> Price: 4 [min_price=1, max_profit=5]
Why: Profit less than max_profit, no update
Result:
Max profit = 5 (buy at 1, sell at 6)
Annotated Code
DSA C#
using System;

class StockTrader
{
    // Variant 1: Single transaction max profit
    public static int MaxProfitSingleTransaction(int[] prices)
    {
        int minPrice = int.MaxValue;
        int maxProfit = 0;
        foreach (int price in prices)
        {
            if (price < minPrice)
                minPrice = price; // update min price to buy low
            else if (price - minPrice > maxProfit)
                maxProfit = price - minPrice; // update max profit if selling now is better
        }
        return maxProfit;
    }

    // Variant 2: Multiple transactions allowed
    public static int MaxProfitMultipleTransactions(int[] prices)
    {
        int profit = 0;
        for (int i = 1; i < prices.Length; i++)
        {
            if (prices[i] > prices[i - 1])
                profit += prices[i] - prices[i - 1]; // accumulate all positive gains
        }
        return profit;
    }

    // Variant 3: At most two transactions
    public static int MaxProfitTwoTransactions(int[] prices)
    {
        int n = prices.Length;
        if (n == 0) return 0;

        int[] leftProfits = new int[n];
        int minPrice = prices[0];
        for (int i = 1; i < n; i++)
        {
            minPrice = Math.Min(minPrice, prices[i]); // lowest price so far
            leftProfits[i] = Math.Max(leftProfits[i - 1], prices[i] - minPrice); // max profit left side
        }

        int maxPrice = prices[n - 1];
        int maxProfit = leftProfits[n - 1];
        int rightProfit = 0;
        for (int i = n - 2; i >= 0; i--)
        {
            maxPrice = Math.Max(maxPrice, prices[i]); // highest price from right
            rightProfit = Math.Max(rightProfit, maxPrice - prices[i]); // max profit right side
            maxProfit = Math.Max(maxProfit, rightProfit + leftProfits[i]); // combine left and right
        }

        return maxProfit;
    }

    static void Main()
    {
        int[] prices = {7, 1, 5, 3, 6, 4};

        Console.WriteLine("Single transaction max profit: " + MaxProfitSingleTransaction(prices));
        Console.WriteLine("Multiple transactions max profit: " + MaxProfitMultipleTransactions(prices));
        Console.WriteLine("At most two transactions max profit: " + MaxProfitTwoTransactions(prices));
    }
}
if (price < minPrice) minPrice = price; // update min price to buy low
track lowest price to buy
else if (price - minPrice > maxProfit) maxProfit = price - minPrice; // update max profit if selling now is better
update max profit if current sell price yields better profit
if (prices[i] > prices[i - 1]) profit += prices[i] - prices[i - 1]; // accumulate all positive gains
sum all positive price differences for multiple transactions
minPrice = Math.Min(minPrice, prices[i]); // lowest price so far
track min price from left for first transaction
leftProfits[i] = Math.Max(leftProfits[i - 1], prices[i] - minPrice); // max profit left side
store max profit achievable up to day i
maxPrice = Math.Max(maxPrice, prices[i]); // highest price from right
track max price from right for second transaction
rightProfit = Math.Max(rightProfit, maxPrice - prices[i]); // max profit right side
max profit achievable from day i to end
maxProfit = Math.Max(maxProfit, rightProfit + leftProfits[i]); // combine left and right
combine profits from two transactions for max total
OutputSuccess
Single transaction max profit: 5 Multiple transactions max profit: 7 At most two transactions max profit: 7
Complexity Analysis
Time: O(n) because we scan the price list once or twice depending on variant
Space: O(n) for the two transactions variant due to extra arrays, O(1) for others
vs Alternative: Naive approach tries all buy-sell pairs with O(n^2) time, which is slower
Edge Cases
Empty price list
Returns 0 profit because no transactions possible
DSA C#
if (n == 0) return 0;
Prices always decreasing
Returns 0 profit because no profitable transaction exists
DSA C#
maxProfit initialized to 0 and never updated
Single day price
Returns 0 profit because cannot sell without buying on different day
DSA C#
for loops do not run if prices.Length < 2
When to Use This Pattern
When you see a problem asking for max profit from stock prices with buy/sell constraints, use buy and sell stock patterns to track min prices and profits efficiently.
Common Mistakes
Mistake: Trying to buy and sell multiple times without summing all positive gains for multiple transactions variant
Fix: Sum all positive price differences between consecutive days
Mistake: Not updating min price before calculating profit in single transaction variant
Fix: Always update min price first before calculating profit
Mistake: For two transactions variant, not combining left and right profits correctly
Fix: Use two arrays or passes to combine max profits from left and right sides
Summary
Find the best times to buy and sell stocks to maximize profit under different transaction rules.
Use when you need to calculate max profit from stock prices with constraints on number of transactions.
Track minimum prices and accumulate profits smartly to avoid checking all pairs.

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