Buy and Sell Stocks All Variants in DSA Go - Time & Space Complexity
We want to understand how the time needed to find the best buy and sell days for stocks changes as the number of days grows.
How does the number of days affect how long our solution takes?
Analyze the time complexity of the following code snippet.
func maxProfit(prices []int) int {
minPrice := prices[0]
maxProfit := 0
for _, price := range prices {
if price < minPrice {
minPrice = price
} else if profit := price - minPrice; profit > maxProfit {
maxProfit = profit
}
}
return maxProfit
}
This code finds the maximum profit from buying and selling a stock once by scanning prices once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single loop through the prices array.
- How many times: Exactly once for each day (n times).
As the number of days increases, the code checks each price once, so the work grows directly with the number of days.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 checks |
| 100 | About 100 checks |
| 1000 | About 1000 checks |
Pattern observation: The operations grow in a straight line with input size.
Time Complexity: O(n)
This means the time to find the best buy and sell days grows directly with the number of days.
[X] Wrong: "Checking every pair of days is necessary to find the max profit."
[OK] Correct: This leads to a slower solution (O(n²)) but scanning once while tracking minimum price is enough.
Understanding this problem's time complexity helps you explain efficient solutions clearly and shows you can find smart ways to scan data once instead of many times.
"What if we allowed multiple buy and sell transactions? How would the time complexity change?"
Practice
Buy and Sell Stocks problem variants?Solution
Step 1: Understand the problem goal
The problem asks to maximize profit by buying and selling stocks on certain days.Step 2: Identify the correct objective
Maximizing profit means choosing days to buy low and sell high, not just counting transactions or prices.Final Answer:
Maximize the profit by choosing the best days to buy and sell stocks -> Option CQuick Check:
Goal = Maximize profit [OK]
- Confusing profit with number of transactions
- Thinking only about highest price day
- Ignoring the buy day in calculations
Solution
Step 1: Understand slice initialization in Go
To create a slice with values, use the literal syntax: []int{values}.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.Final Answer:
prices := []int{7, 1, 5, 3, 6} -> Option AQuick Check:
Slice literal = []int{values} [OK]
- Using array syntax instead of slice
- Using new() incorrectly for slices
- Creating empty slices without values
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}))Solution
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=5Step 2: Return maxProfit
maxProfit is 5 after loop ends.Final Answer:
5 -> Option AQuick Check:
Max profit = 5 [OK]
- Not updating minPrice correctly
- Calculating profit before updating minPrice
- Returning wrong variable
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
}Solution
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.Step 2: Identify fix
Start loop from i=1 to avoid negative index access.Final Answer:
Index out of range error due to accessing prices[i-1] when i=0 -> Option DQuick Check:
Loop index must start at 1 to avoid error [OK]
- Starting loop at 0 but accessing i-1
- Ignoring runtime errors
- Not testing with small input arrays
[3, 3, 5, 0, 0, 3, 1, 4], what is the maximum profit with at most two transactions?Solution
Step 1: Understand two transactions limit
We can buy and sell stocks at most twice to maximize profit.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 = 6Final Answer:
6 -> Option BQuick Check:
Two transactions max profit = 6 [OK]
- Counting overlapping transactions
- Ignoring zero price days
- Calculating only one transaction profit
Ready to prove it?
Pass the test and this pattern moves unknown
