Bird
Raised Fist0
DSA Pythonprogramming~10 mins

Buy and Sell Stocks All Variants in DSA Python - Interactive Practice

Choose your learning style10 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to find the maximum profit from a single buy and sell.

DSA Python
def max_profit(prices):
    min_price = float('inf')
    max_profit = 0
    for price in prices:
        if price < [1]:
            min_price = price
        elif price - min_price > max_profit:
            max_profit = price - min_price
    return max_profit
Drag options to blanks, or click blank then click option'
Amax_price
Bmax_profit
Cmin_price
Dprice
Attempts:
3 left
💡 Hint
Common Mistakes
Using max_price instead of min_price
Updating max_profit incorrectly
Not initializing min_price properly
2fill in blank
medium

Complete the code to calculate max profit with unlimited transactions.

DSA Python
def max_profit_unlimited(prices):
    profit = 0
    for i in range(1, len(prices)):
        if prices[i] > [1]:
            profit += prices[i] - prices[i-1]
    return profit
Drag options to blanks, or click blank then click option'
Aprices[i-1]
Bprices[i]
Cprices[0]
Dprices[i+1]
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing with prices[i] instead of prices[i-1]
Using prices[i+1] which may cause index error
Adding profit when price is not increasing
3fill in blank
hard

Fix the error in the code to find max profit with at most two transactions.

DSA Python
def max_profit_two_transactions(prices):
    n = len(prices)
    left_profits = [0] * n
    right_profits = [0] * n

    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] - [1])

    max_price = prices[-1]
    for i in range(n-2, -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])
    return max_profit
Drag options to blanks, or click blank then click option'
Amin_price
Bmax_price
Cprices[i-1]
Dprices[i]
Attempts:
3 left
💡 Hint
Common Mistakes
Using max_price instead of min_price
Using prices[i] instead of min_price
Confusing left and right profits arrays
4fill in blank
hard

Fill both blanks to implement max profit with cooldown period.

DSA Python
def max_profit_cooldown(prices):
    n = len(prices)
    if n <= 1:
        return 0
    sell = [0] * n
    buy = [0] * n
    buy[0] = -prices[0]
    for i in range(1, n):
        buy[i] = max(buy[i-1], sell[i-2] - [1]) if i > 1 else max(buy[i-1], -prices[i])
        sell[i] = max(sell[i-1], buy[i-1] + [2])
    return sell[-1]
Drag options to blanks, or click blank then click option'
Aprices[i]
Bprices[i-1]
Cprices[i+1]
Dprices[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Using prices[i-1] instead of prices[i]
Using prices[0] which is incorrect for all days
Mixing up buy and sell calculations
5fill in blank
hard

Fill all three blanks to implement max profit with at most k transactions.

DSA Python
def max_profit_k_transactions(k, prices):
    if not prices or k == 0:
        return 0
    n = len(prices)
    if k >= n // 2:
        profit = 0
        for i in range(1, n):
            profit += max(0, prices[i] - prices[i-1])
        return profit

    dp = [[0] * n for _ in range(k+1)]
    for i in range(1, k+1):
        max_diff = -prices[0]
        for j in range(1, n):
            dp[i][j] = max(dp[i][j-1], prices[j] + [1])
            max_diff = max(max_diff, dp[i-1][j] - [2])
        
    return dp[k][n-1]
Drag options to blanks, or click blank then click option'
Amax_diff
Bprices[j]
Cdp[i-1][j-1]
Ddp[i-1][j]
Attempts:
3 left
💡 Hint
Common Mistakes
Using dp[i-1][j-1] instead of dp[i-1][j]
Confusing max_diff with prices[j]
Not updating max_diff correctly inside the loop

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