Buy and Sell Stocks All Variants in DSA Rust - Time & Space Complexity
We want to understand how the time needed to find the best buy and sell days changes as the number of days grows.
How does the number of price checks and comparisons grow when we have more days?
Analyze the time complexity of the following code snippet.
fn max_profit(prices: &[i32]) -> i32 {
let mut min_price = i32::MAX;
let mut max_profit = 0;
for &price in prices {
if price < min_price {
min_price = price;
} else if price - min_price > max_profit {
max_profit = price - min_price;
}
}
max_profit
}
This code finds the best profit from buying and selling once by scanning prices once.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: One loop through the price list.
- 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 work grows in a straight line with input size.
Time Complexity: O(n)
This means the time needed grows directly with the number of days you have prices for.
[X] Wrong: "We need to check every pair of days to find the best profit, so it must be O(n²)."
[OK] Correct: This code smartly keeps track of the lowest price so far and only compares current price to it, avoiding checking all pairs.
Understanding this pattern helps you solve many stock trading problems efficiently and shows you can find smart shortcuts instead of brute force.
"What if we wanted to allow 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 key objective
Maximizing profit means buying low and selling high at the best possible times.Final Answer:
Maximize the profit by choosing the best days to buy and sell stocks -> Option AQuick Check:
Goal = Maximize profit [OK]
- Confusing profit maximization with minimizing transactions
- Ignoring the buy before sell rule
- Thinking the goal is to find average price
Solution
Step 1: Identify Rust vector syntax
In Rust, vectors are created usingvec![...]macro.Step 2: Check each option
let prices = vec![7, 1, 5, 3, 6, 4]; usesvec![...], which is correct. let prices = [7, 1, 5, 3, 6, 4]; is an array, not a vector. let prices = (7, 1, 5, 3, 6, 4); is a tuple. let prices = {7, 1, 5, 3, 6, 4}; is invalid syntax.Final Answer:
let prices = vec![7, 1, 5, 3, 6, 4]; -> Option BQuick Check:
Vector = vec![...] syntax [OK]
- Using array syntax instead of vector
- Using tuple instead of vector
- Invalid curly braces for initialization
fn max_profit(prices: Vec<i32>) -> i32 {
let mut min_price = i32::MAX;
let mut max_profit = 0;
for price in prices {
if price < min_price {
min_price = price;
} else if price - min_price > max_profit {
max_profit = price - min_price;
}
}
max_profit
}
fn main() {
let prices = vec![7, 1, 5, 3, 6, 4];
println!("{}", max_profit(prices));
}Solution
Step 1: Trace the loop to find min_price and max_profit
Start with min_price = MAX, max_profit = 0. Prices: 7,1,5,3,6,4 - price=7: min_price=7, max_profit=0 - price=1: min_price=1, max_profit=0 - price=5: profit=5-1=4 > 0, max_profit=4 - price=3: profit=3-1=2 < 4, max_profit=4 - price=6: profit=6-1=5 > 4, max_profit=5 - price=4: profit=4-1=3 < 5, max_profit=5Step 2: Return max_profit
max_profit is 5 after loop ends.Final Answer:
5 -> Option DQuick Check:
Max profit = 5 [OK]
- Not updating min_price correctly
- Calculating profit before updating min_price
- Confusing max profit with max price
fn max_profit(prices: Vec<i32>) -> i32 {
let mut profit = 0;
for i in 0..prices.len() {
if prices[i] > prices[i - 1] {
profit += prices[i] - prices[i - 1];
}
}
profit
}Solution
Step 1: Analyze loop 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 bounds.Step 2: Identify fix
Loop should start from i=1 to avoid negative index access.Final Answer:
Index out of bounds error when i = 0 -> Option AQuick Check:
Negative index access causes runtime error [OK]
- Starting loop at 0 causing invalid index
- Not checking vector length before access
- Assuming negative indices are valid
[3, 3, 5, 0, 0, 3, 1, 4], what is the maximum profit achievable with at most two transactions (buy-sell pairs)?Solution
Step 1: Understand two transactions limit
We can buy and sell at most twice to maximize profit.Step 2: Find best two transactions
Prices: 3,3,5,0,0,3,1,4 - First transaction: buy at 3 (day 0), sell at 5 (day 2), profit = 2 - Second transaction: buy at 0 (day 3), sell at 4 (day 7), profit = 4 Total profit = 2 + 4 = 6Final Answer:
6 -> Option CQuick Check:
Sum of two best profits = 6 [OK]
- Counting overlapping transactions
- Choosing wrong buy/sell days
- Ignoring the two transactions limit
Ready to prove it?
Pass the test and this pattern moves unknown
