0
0
DSA Cprogramming

Buy and Sell Stocks All Variants in DSA C

Choose your learning style9 modes available
Mental Model
We want to find the best times to buy and sell stocks to make the most money. Different rules change how many times we can trade or if there are fees.
Analogy: Imagine you buy fruits at a low price and sell them later at a higher price. Sometimes you can only sell once, sometimes many times, and sometimes you pay a small fee each time you sell.
Prices: 7 -> 1 -> 5 -> 3 -> 6 -> 4 -> null
Buy low, sell high to earn profit.
Dry Run Walkthrough
Input: prices: [7, 1, 5, 3, 6, 4], max 2 transactions allowed
Goal: Find the maximum profit by buying and selling at most twice
Step 1: Initialize profit arrays for 0 to 2 transactions
profit[0]=0, profit[1]=0, profit[2]=0
Why: We start with no profit before any trades
Step 2: First pass: track max profit from left to right for 1 transaction
min_price=7, profit[1]=0 after day 1
min_price=1, profit[1]=0 after day 2
min_price=1, profit[1]=4 after day 3
min_price=1, profit[1]=4 after day 4
min_price=1, profit[1]=5 after day 5
min_price=1, profit[1]=5 after day 6
Why: We find best profit if we sell on or before each day with one transaction
Step 3: Second pass: track max profit from right to left for second transaction
max_price=4, profit[2]=5 after day 6
max_price=6, profit[2]=5 after day 5
max_price=6, profit[2]=7 after day 4
max_price=6, profit[2]=7 after day 3
max_price=7, profit[2]=7 after day 2
max_price=7, profit[2]=7 after day 1
Why: We combine profits from two transactions to find max total profit
Result:
Final max profit = 7
Annotated Code
DSA C
#include <stdio.h>
#include <stdlib.h>

int max(int a, int b) {
    return (a > b) ? a : b;
}

int maxProfitTwoTransactions(int* prices, int pricesSize) {
    if (pricesSize == 0) return 0;
    int* profit = (int*)calloc(pricesSize, sizeof(int));

    int min_price = prices[0];
    for (int i = 1; i < pricesSize; i++) {
        min_price = (prices[i] < min_price) ? prices[i] : min_price; // update min price
        profit[i] = max(profit[i - 1], prices[i] - min_price); // max profit if sold today
    }

    int max_price = prices[pricesSize - 1];
    int max_total_profit = profit[pricesSize - 1];
    for (int i = pricesSize - 2; i >= 0; i--) {
        max_price = (prices[i] > max_price) ? prices[i] : max_price; // update max price
        int total_profit = max_price - prices[i] + profit[i]; // profit if buy today and sell later plus previous profit
        max_total_profit = max(max_total_profit, total_profit); // max of all
    }

    free(profit);
    return max_total_profit;
}

int main() {
    int prices[] = {7, 1, 5, 3, 6, 4};
    int size = sizeof(prices) / sizeof(prices[0]);
    int max_profit = maxProfitTwoTransactions(prices, size);
    printf("Max profit with at most 2 transactions: %d\n", max_profit);
    return 0;
}
min_price = (prices[i] < min_price) ? prices[i] : min_price;
update minimum price seen so far to buy low
profit[i] = max(profit[i - 1], prices[i] - min_price);
calculate max profit if sold on day i with one transaction
max_price = (prices[i] > max_price) ? prices[i] : max_price;
update maximum price seen so far from right to buy high later
int total_profit = max_price - prices[i] + profit[i];
combine profit of second transaction starting at day i with first transaction profit
max_total_profit = max(max_total_profit, total_profit);
keep track of maximum combined profit
OutputSuccess
Max profit with at most 2 transactions: 7
Complexity Analysis
Time: O(n) because we scan the prices array twice, once forward and once backward
Space: O(n) for the profit array storing max profit up to each day
vs Alternative: Naive approach tries all pairs of buy/sell days for each transaction leading to O(n^2) or worse; this approach is efficient and linear
Edge Cases
empty prices array
returns 0 profit because no transactions possible
DSA C
if (pricesSize == 0) return 0;
prices array with one element
returns 0 profit because cannot sell after buying
DSA C
if (pricesSize == 0) return 0;
prices always decreasing
returns 0 profit because no profitable transactions
DSA C
profit[i] = max(profit[i - 1], prices[i] - min_price);
When to Use This Pattern
When asked to maximize stock trading profit with limits on transactions or fees, use dynamic programming with forward and backward passes to combine profits efficiently.
Common Mistakes
Mistake: Trying to check all buy/sell pairs for multiple transactions leading to slow code
Fix: Use two passes with arrays to store max profit up to each day and from each day
Mistake: Not updating min_price or max_price correctly causing wrong profit calculation
Fix: Always update min_price when a lower price is found and max_price when a higher price is found
Summary
Calculates maximum profit from stock prices with constraints on number of transactions.
Use when you want to find best buy/sell strategy with limited trades or fees.
The key is to combine profits from two directions to find the best total profit.