Bird
Raised Fist0
DSA Pythonprogramming

Buy and Sell Stocks All Variants in DSA Python

Choose your learning style10 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 have a fruit stand and prices change daily. You want to buy fruit cheap and sell it high. Sometimes you can only buy and sell once, sometimes many times, and sometimes you pay a fee each time you sell.
Day:    0    1    2    3    4    5
Price: 100 -> 180 -> 260 -> 310 -> 40 -> 535
Buy?   ↑
Sell?        ↑
Profit: 0    ?    ?    ?    ?    ?
Dry Run Walkthrough
Input: prices = [100, 180, 260, 310, 40, 535], max 2 transactions allowed
Goal: Find the maximum profit by buying and selling at most twice
Step 1: Start first transaction: buy at day 0 price 100
Day 0: Buy at 100, profit so far 0
Why: We pick the lowest price to start the first buy
Step 2: Sell first transaction at day 3 price 310
Transaction 1: Buy 100 -> Sell 310, profit 210
Why: Selling at 310 gives max profit for first transaction
Step 3: Start second transaction: buy at day 4 price 40
Transaction 2: Buy at 40, total profit 210
Why: Buy low again to maximize second transaction profit
Step 4: Sell second transaction at day 5 price 535
Transaction 2: Buy 40 -> Sell 535, profit 495 + 210 = 705 total
Why: Selling at 535 maximizes second transaction profit
Result:
Maximum profit = 705
Annotated Code
DSA Python
from typing import List

class StockTrader:
    def max_profit_two_transactions(self, prices: List[int]) -> int:
        if not prices:
            return 0

        n = len(prices)
        left_profits = [0] * n
        right_profits = [0] * (n + 1)

        # Left to right: max profit if sold on or before day i
        min_price = prices[0]
        for i in range(1, n):
            min_price = min(min_price, prices[i])
            left_profits[i] = max(left_profits[i - 1], prices[i] - min_price)

        # Right to left: max profit if bought on or after day i
        max_price = prices[-1]
        for i in range(n - 1, -1, -1):
            max_price = max(max_price, prices[i])
            right_profits[i] = max(right_profits[i + 1], max_price - prices[i])

        max_profit = 0
        for i in range(n):
            max_profit = max(max_profit, left_profits[i] + right_profits[i + 1])

        return max_profit


if __name__ == "__main__":
    prices = [100, 180, 260, 310, 40, 535]
    trader = StockTrader()
    result = trader.max_profit_two_transactions(prices)
    print(result)
min_price = prices[0]
initialize minimum price for first pass
for i in range(1, n):
iterate forward to calculate max profit if sold by day i
min_price = min(min_price, prices[i])
update minimum price seen so far
left_profits[i] = max(left_profits[i - 1], prices[i] - min_price)
update max profit for first transaction up to day i
max_price = prices[-1]
initialize maximum price for second pass
for i in range(n - 1, -1, -1):
iterate backward to calculate max profit if bought on or after day i
max_price = max(max_price, prices[i])
update maximum price seen so far from right
right_profits[i] = max(right_profits[i + 1], max_price - prices[i])
update max profit for second transaction starting day i
for i in range(n):
combine profits from two transactions to find max total
max_profit = max(max_profit, left_profits[i] + right_profits[i + 1])
update max profit by splitting transactions at day i
OutputSuccess
705
Complexity Analysis
Time: O(n) because we scan the price list forward and backward once each
Space: O(n) because we store two arrays for profits at each day
vs Alternative: Naive approach tries all pairs of buy/sell twice with O(n^2) time, this is much faster
Edge Cases
empty price list
returns 0 profit because no transactions possible
DSA Python
if not prices:
    return 0
prices always decreasing
returns 0 profit because no profitable transactions
DSA Python
left_profits[i] = max(left_profits[i - 1], prices[i] - min_price)
only one price
returns 0 profit because cannot sell after buying
DSA Python
if not prices:
    return 0
When to Use This Pattern
When you see a problem asking for max profit with at most k transactions, use dynamic programming with forward and backward passes to combine profits.
Common Mistakes
Mistake: Trying to buy and sell multiple times without tracking transaction limits
Fix: Use arrays to track max profit for allowed transactions and combine results carefully
Mistake: Not handling empty or single-element price lists
Fix: Add guard clauses to return 0 profit for these edge cases
Summary
Calculates maximum profit from stock prices with at most two buy-sell transactions.
Use when you want to maximize profit with limited number of trades.
Split the problem into two parts: max profit before day i and max profit after day i, then combine.

Practice

(1/5)
1. What is the main goal when solving the Buy and Sell Stocks problem variants?
easy
A. Find the day with the lowest stock price only
B. Minimize the number of transactions regardless of profit
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 goal

    The problem asks to find the best days to buy and sell stocks to get the highest profit.
  2. Step 2: Identify the objective

    Maximizing profit means buying low and selling high at the right times.
  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 prices or counts [OK]
Common Mistakes:
  • Thinking the goal is to minimize transactions
  • Only finding lowest price day without selling
  • Calculating averages instead of profit
2. Which of the following Python code snippets correctly initializes variables to track minimum price and maximum profit for the stock problem?
easy
A. min_price = float('inf'); max_profit = 0
B. min_price = 0; max_profit = float('-inf')
C. min_price = None; max_profit = None
D. min_price = 0; max_profit = 0

Solution

  1. Step 1: Understand initialization needs

    We want min_price to start very high so any price is lower, and max_profit to start at zero.
  2. Step 2: Check each option

    min_price = float('inf'); max_profit = 0 sets min_price to infinity and max_profit to zero, which is correct for tracking minimum and maximum values.
  3. Final Answer:

    min_price = float('inf'); max_profit = 0 -> Option A
  4. Quick Check:

    Initialization = min_price high, max_profit zero [OK]
Hint: Use infinity for min_price start, zero for max_profit [OK]
Common Mistakes:
  • Setting min_price to zero causes wrong minimum tracking
  • Using None without checks causes errors
  • Setting max_profit to negative infinity can confuse logic
3. What is the output of the following code snippet for prices = [7,1,5,3,6,4]?
min_price = float('inf')
max_profit = 0
for price in prices:
    if price < min_price:
        min_price = price
    elif price - min_price > max_profit:
        max_profit = price - min_price
print(max_profit)
medium
A. 6
B. 7
C. 4
D. 5

Solution

  1. Step 1: Trace the loop with given prices

    Prices: 7,1,5,3,6,4 - Start min_price=inf, max_profit=0 - price=7: min_price=7 - price=1: min_price=1 (lower) - price=5: profit=5-1=4 > 0, max_profit=4 - price=3: profit=3-1=2 < 4, no change - price=6: profit=6-1=5 > 4, max_profit=5 - price=4: profit=4-1=3 < 5, no change
  2. Step 2: Final max_profit after loop

    max_profit is 5 after checking all prices.
  3. Final Answer:

    5 -> Option D
  4. Quick Check:

    Max profit = 5 [OK]
Hint: Track min price and update max profit on higher prices [OK]
Common Mistakes:
  • Confusing max profit with max price
  • Not updating min_price correctly
  • Calculating profit incorrectly
4. Identify the error in this code snippet for the stock problem:
prices = [7,1,5,3,6,4]
min_price = 0
max_profit = 0
for price in prices:
    if price < min_price:
        min_price = price
    elif price - min_price > max_profit:
        max_profit = price - min_price
print(max_profit)
medium
A. Loop should start from second element
B. min_price initialized to 0 instead of a high value
C. max_profit should start at float('inf')
D. Using elif instead of if causes logic error

Solution

  1. Step 1: Check variable initialization

    min_price is set to 0, but prices include values greater than 0, so min_price never updates to actual minimum (1).
  2. Step 2: Effect of wrong min_price initialization

    Since min_price=0, price < min_price is never true, so min_price stays 0, causing incorrect profit calculations.
  3. Final Answer:

    min_price initialized to 0 instead of a high value -> Option B
  4. Quick Check:

    min_price must start high to track minimum [OK]
Hint: Initialize min_price to infinity, not zero [OK]
Common Mistakes:
  • Starting min_price at zero causes wrong minimum tracking
  • Confusing max_profit initialization
  • Thinking elif causes logic error here
5. Given the prices array [3,3,5,0,0,3,1,4], what is the maximum profit with at most two transactions?
hard
A. 6
B. 7
C. 5
D. 4

Solution

  1. Step 1: Understand two transactions limit

    We can buy and sell stocks at most twice to maximize total profit.
  2. Step 2: Calculate profits for two transactions

    First transaction: buy at 3, sell at 5 = 2 profit Second transaction: buy at 0, sell at 4 = 4 profit Total profit = 2 + 4 = 6
  3. Final Answer:

    6 -> Option A
  4. Quick Check:

    Two transactions max profit = 6 [OK]
Hint: Split array, find max profit in two parts [OK]
Common Mistakes:
  • Counting overlapping transactions
  • Only considering one transaction
  • 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