Bird
Raised Fist0
DSA Pythonprogramming~10 mins

Buy and Sell Stocks All Variants in DSA Python - Execution Trace

Choose your learning style10 modes available
Concept Flow - Buy and Sell Stocks All Variants
Start: Prices Array
↓
Choose Variant
↓
One Transaction
↓
Track Min Price
↓
Calculate Max Profit
↓
Return Max Profit Result
↓
End
The flow starts with the prices array, then chooses the variant of the problem, and follows the specific steps to calculate max profit accordingly.
Execution Sample
DSA Python
prices = [7,1,5,3,6,4]
min_price = prices[0]
max_profit = 0
for price in prices:
    min_price = min(min_price, price)
    max_profit = max(max_profit, price - min_price)
print(max_profit)
This code finds the max profit from one buy-sell transaction by tracking the minimum price and max profit.
Execution Table
StepOperationCurrent PriceMin PriceMax ProfitVisual State
1Initialize770[7] min_price=7, max_profit=0
2Check price=7770[7] min_price=7, max_profit=0
3Check price=1110[7,1] min_price=1, max_profit=0
4Check price=5514[7,1,5] min_price=1, max_profit=4 (5-1)
5Check price=3314[7,1,5,3] min_price=1, max_profit=4
6Check price=6615[7,1,5,3,6] min_price=1, max_profit=5 (6-1)
7Check price=4415[7,1,5,3,6,4] min_price=1, max_profit=5
8End-15Final max_profit=5
💡 All prices checked, max profit found as 5
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7Final
min_price77111111
max_profit00044555
price-715364-
Key Moments - 3 Insights
Why do we update min_price before calculating max_profit?
Because max_profit depends on the lowest price seen so far. Updating min_price first ensures we calculate profit with the smallest buy price (see steps 3 and 4 in execution_table).
Why max_profit does not decrease even if price drops later?
max_profit only updates if current profit (price - min_price) is higher. It never decreases to keep the best profit found so far (see steps 5 to 7).
What if prices are always decreasing?
max_profit stays 0 because no profitable transaction exists. min_price updates but price - min_price never becomes positive (not shown in this example but implied).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 4, what is the max_profit value?
A4
B5
C0
D1
💡 Hint
Check the 'Max Profit' column at Step 4 in execution_table
At which step does min_price first change from 7 to 1?
AStep 2
BStep 3
CStep 4
DStep 5
💡 Hint
Look at the 'Min Price' column in variable_tracker after Step 3
If prices were [7,6,4,3,1], what would max_profit be at the end?
A6
B0
C1
D7
💡 Hint
Consider that prices only decrease, so no profitable buy-sell pair exists
Concept Snapshot
Buy and Sell Stocks Variants:
- One transaction: Track min price and max profit
- Multiple transactions: Sum all positive differences
- With cooldown: Use states to track cooldown days
- Always update min price before profit
- Profit never decreases once max found
Full Transcript
This concept covers different ways to find maximum profit from stock prices. The simplest is one transaction: track the lowest price so far and calculate profit by subtracting it from current price. Update max profit if current profit is higher. The flow starts by reading prices, choosing the variant, then applying the logic step-by-step. The example code tracks min_price and max_profit through the prices array. The execution table shows each step with current price, min price, and max profit updates. Key moments clarify why min_price updates before max_profit and why max_profit never decreases. The visual quiz tests understanding of these steps and edge cases. The snapshot summarizes the main rules for quick recall.

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