Bird
Raised Fist0
DSA Goprogramming~10 mins

Buy and Sell Stocks All Variants in DSA Go - 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 Go
func maxProfit(prices []int) int {
    minPrice := prices[0]
    maxProfit := 0
    for i := 1; i < len(prices); i++ {
        if prices[i] < [1] {
            minPrice = prices[i]
        } else if prices[i]-minPrice > maxProfit {
            maxProfit = prices[i] - minPrice
        }
    }
    return maxProfit
}
Drag options to blanks, or click blank then click option'
AmaxProfit
Bprices[i]
CminPrice
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Using maxProfit instead of minPrice in the comparison.
Not updating minPrice correctly.
2fill in blank
medium

Complete the code to calculate maximum profit with unlimited transactions.

DSA Go
func maxProfit(prices []int) int {
    profit := 0
    for i := 1; i < len(prices); i++ {
        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]
C0
Dprices[0]
Attempts:
3 left
💡 Hint
Common Mistakes
Comparing prices[i] with prices[i] instead of prices[i-1].
Adding profit when prices decrease.
3fill in blank
hard

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

DSA Go
func maxProfit(prices []int) int {
    if len(prices) == 0 {
        return 0
    }
    firstBuy, firstSell := -prices[0], 0
    secondBuy, secondSell := -prices[0], 0
    for i := 1; i < len(prices); i++ {
        firstBuy = max(firstBuy, -prices[i])
        firstSell = max(firstSell, firstBuy + prices[i])
        secondBuy = max(secondBuy, firstSell - [1])
        secondSell = max(secondSell, secondBuy + prices[i])
    }
    return secondSell
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
Drag options to blanks, or click blank then click option'
Aprices[0]
Bprices[i]
CfirstBuy
DfirstSell
Attempts:
3 left
💡 Hint
Common Mistakes
Using prices[0] instead of prices[i] in secondBuy update.
Mixing variables in the calculation.
4fill in blank
hard

Fill both blanks to implement max profit with cooldown period after selling.

DSA Go
func maxProfit(prices []int) int {
    n := len(prices)
    if n <= 1 {
        return 0
    }
    sell, prevSell, buy := 0, 0, -prices[0]
    for i := 1; i < n; i++ {
        prevBuy := buy
        buy = max(buy, [1] - prices[i])
        [2] = max(sell, prevBuy + prices[i])
        prevSell = sell
        sell = [2]
    }
    return sell
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
Drag options to blanks, or click blank then click option'
AprevSell
BprevBuy
Csell
Dbuy
Attempts:
3 left
💡 Hint
Common Mistakes
Using sell instead of prevSell in buy update.
Confusing prevBuy and buy in sell update.
5fill in blank
hard

Fill all three blanks to implement max profit with transaction fee.

DSA Go
func maxProfit(prices []int, fee int) int {
    n := len(prices)
    if n == 0 {
        return 0
    }
    cash, hold := 0, -prices[0]
    for i := 1; i < n; i++ {
        cash = max(cash, hold + prices[i] - [1])
        hold = max(hold, cash - [2])
    }
    return cash
}

func max(a, b int) int {
    if a > b {
        return a
    }
    return b
}
Drag options to blanks, or click blank then click option'
Afee
Bprices[i]
Attempts:
3 left
💡 Hint
Common Mistakes
Subtracting fee when buying instead of selling.
Mixing price and fee in wrong places.

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 highest 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 maximize profit by buying and selling stocks on certain days.
  2. Step 2: Identify the correct objective

    Maximizing profit means choosing days to buy low and sell high, not just counting transactions or prices.
  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:
  • Confusing profit with number of transactions
  • Thinking only about highest price day
  • Ignoring the buy day in calculations
2. Which of the following Go code snippets correctly initializes a slice to store stock prices for 5 days?
easy
A. prices := []int{7, 1, 5, 3, 6}
B. prices := [5]int{7, 1, 5, 3, 6}
C. prices := make([]int, 5, 5)
D. prices := new([]int{7, 1, 5, 3, 6})

Solution

  1. Step 1: Understand slice initialization in Go

    To create a slice with values, use the literal syntax: []int{values}.
  2. Step 2: Check each option

    prices := []int{7, 1, 5, 3, 6} correctly creates a slice with given values. prices := [5]int{7, 1, 5, 3, 6} creates an array, not a slice. prices := make([]int, 5, 5) creates an empty slice of length 5 but no values. prices := new([]int{7, 1, 5, 3, 6}) is invalid syntax.
  3. Final Answer:

    prices := []int{7, 1, 5, 3, 6} -> Option A
  4. Quick Check:

    Slice literal = []int{values} [OK]
Hint: Use []int{...} to create slices with values directly [OK]
Common Mistakes:
  • Using array syntax instead of slice
  • Using new() incorrectly for slices
  • Creating empty slices without values
3. What is the output of the following Go code that finds the max profit with only one transaction?
func maxProfit(prices []int) int {
    minPrice := prices[0]
    maxProfit := 0
    for _, price := range prices {
        if price < minPrice {
            minPrice = price
        } else if price - minPrice > maxProfit {
            maxProfit = price - minPrice
        }
    }
    return maxProfit
}

fmt.Println(maxProfit([]int{7,1,5,3,6,4}))
medium
A. 5
B. 6
C. 4
D. 7

Solution

  1. Step 1: Trace the loop to find minPrice and maxProfit

    Start minPrice=7, maxProfit=0. Iterate prices: - price=7: minPrice=7, maxProfit=0 - price=1: minPrice=1 (lower) - price=5: profit=5-1=4 >0, maxProfit=4 - price=3: profit=3-1=2 <4, maxProfit=4 - price=6: profit=6-1=5 >4, maxProfit=5 - price=4: profit=4-1=3 <5, maxProfit=5
  2. Step 2: Return maxProfit

    maxProfit is 5 after loop ends.
  3. Final Answer:

    5 -> Option A
  4. Quick Check:

    Max profit = 5 [OK]
Hint: Track min price and update max profit during iteration [OK]
Common Mistakes:
  • Not updating minPrice correctly
  • Calculating profit before updating minPrice
  • Returning wrong variable
4. Identify the bug in this Go function that tries to calculate max profit with unlimited transactions:
func maxProfit(prices []int) int {
    profit := 0
    for i := 0; i < len(prices); i++ {
        if prices[i] > prices[i-1] {
            profit += prices[i] - prices[i-1]
        }
    }
    return profit
}
medium
A. prices slice is not initialized
B. Incorrect profit calculation logic
C. Missing return statement
D. Index out of range error due to accessing prices[i-1] when i=0

Solution

  1. Step 1: Check loop and index usage

    The loop starts at i=0, but code accesses prices[i-1], which is prices[-1] at i=0, causing index out of range error.
  2. Step 2: Identify fix

    Start loop from i=1 to avoid negative index access.
  3. Final Answer:

    Index out of range error due to accessing prices[i-1] when i=0 -> Option D
  4. Quick Check:

    Loop index must start at 1 to avoid error [OK]
Hint: Avoid negative indices by starting loop at 1 [OK]
Common Mistakes:
  • Starting loop at 0 but accessing i-1
  • Ignoring runtime errors
  • Not testing with small input arrays
5. Given the prices [3, 3, 5, 0, 0, 3, 1, 4], what is the maximum profit with at most two transactions?
hard
A. 7
B. 6
C. 5
D. 8

Solution

  1. Step 1: Understand two transactions limit

    We can buy and sell stocks at most twice to maximize profit.
  2. Step 2: Calculate max profit with two transactions

    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
  3. Final Answer:

    6 -> Option B
  4. Quick Check:

    Two transactions max profit = 6 [OK]
Hint: Split array, find max profit left and right, sum max [OK]
Common Mistakes:
  • Counting overlapping transactions
  • Ignoring zero price days
  • Calculating only one transaction profit
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