Bird
Raised Fist0
DSA Rustprogramming~10 mins

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

Choose your learning style10 modes available
Concept Flow - Buy and Sell Stocks All Variants
Start with prices array
↓
Choose variant: single transaction / multiple / cooldown / fee
↓
Initialize variables: buy_price, profit, cooldown, fee
↓
Iterate over prices
↓
Update buy_price or profit based on variant rules
↓
Apply cooldown or fee if needed
↓
End iteration
↓
Return max profit
The flow starts with the prices array, selects the variant, iterates over prices updating buy price and profit according to rules, applies cooldown or fee if needed, and finally returns the maximum profit.
Execution Sample
DSA Rust
let prices = vec![7,1,5,3,6,4];
let mut min_price = i32::MAX;
let mut max_profit = 0;
for price in prices {
    min_price = min_price.min(price);
    max_profit = max_profit.max(price - min_price);
}
println!("{}", max_profit);
This code finds the maximum profit from a single buy-sell transaction by tracking the minimum price and maximum profit while iterating through prices.
Execution Table
StepOperationCurrent Pricemin_pricemax_profitVisual State
1Initialize min_price and max_profit-∞0[]
2Price=7: min_price=min(∞,7)770[7]
3Price=1: min_price=min(7,1)110[7 -> 1]
4Price=5: max_profit=max(0,5-1)514[7 -> 1 -> 5]
5Price=3: max_profit=max(4,3-1)314[7 -> 1 -> 5 -> 3]
6Price=6: max_profit=max(4,6-1)615[7 -> 1 -> 5 -> 3 -> 6]
7Price=4: max_profit=max(5,4-1)415[7 -> 1 -> 5 -> 3 -> 6 -> 4]
8End iteration-15[7 -> 1 -> 5 -> 3 -> 6 -> 4]
💡 All prices processed; max_profit = 5
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5After Step 6After Step 7Final
min_price∞7111111
max_profit00044555
Key Moments - 3 Insights
Why do we update min_price even if current price is higher than min_price?
Because min_price tracks the lowest price so far to maximize profit later. See execution_table rows 2 and 3 where min_price updates to 7 then 1.
Why do we calculate max_profit as price - min_price?
Because profit is selling price minus buying price. We use min_price as the best buying price so far. See execution_table rows 4-7 where max_profit updates using price - min_price.
Why does max_profit not update when price is less than min_price?
Because selling at a lower price than min_price would reduce profit. Instead, min_price updates to the lower price. See execution_table row 3.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table at Step 4, what is max_profit?
A0
B4
C5
D1
💡 Hint
Check the max_profit column at Step 4 in execution_table.
At which step does min_price become 1?
AStep 2
BStep 4
CStep 3
DStep 5
💡 Hint
Look at min_price column in execution_table rows.
If prices were all increasing, how would max_profit change?
AIt would increase steadily
BIt would decrease
CIt would stay zero
DIt would fluctuate randomly
💡 Hint
Consider how max_profit updates as price - min_price in execution_table.
Concept Snapshot
Buy and Sell Stocks (Single Transaction):
- Track min_price (lowest so far)
- Track max_profit (max difference price - min_price)
- Iterate prices, update min_price and max_profit
- Return max_profit

Variants add cooldown, fees, or multiple transactions with adjusted logic.
Full Transcript
This visualization shows how to find the maximum profit from buying and selling stocks once. We start with the prices array and initialize min_price to infinity and max_profit to zero. As we go through each price, we update min_price if the current price is lower. We calculate potential profit as current price minus min_price and update max_profit if this is higher. The process continues until all prices are checked. The final max_profit is the answer. Key points include always updating min_price to track the lowest buying price and calculating profit as selling price minus buying price. The quiz checks understanding of these updates at specific steps.

Practice

(1/5)
1. What is the main goal when solving the Buy and Sell Stocks problem variants?
easy
A. Maximize the profit by choosing the best days to buy and sell stocks
B. Minimize the number of transactions regardless of profit
C. Find the stock price on the last day
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 key objective

    Maximizing profit means buying low and selling high at the best possible times.
  3. Final Answer:

    Maximize the profit by choosing the best days to buy and sell stocks -> Option A
  4. Quick Check:

    Goal = Maximize profit [OK]
Hint: Focus on profit maximization, not just transactions [OK]
Common Mistakes:
  • Confusing profit maximization with minimizing transactions
  • Ignoring the buy before sell rule
  • Thinking the goal is to find average price
2. Which of the following Rust code snippets correctly initializes a vector of stock prices for the Buy and Sell Stocks problem?
easy
A. let prices = {7, 1, 5, 3, 6, 4};
B. let prices = vec![7, 1, 5, 3, 6, 4];
C. let prices = (7, 1, 5, 3, 6, 4);
D. let prices = [7, 1, 5, 3, 6, 4];

Solution

  1. Step 1: Identify Rust vector syntax

    In Rust, vectors are created using vec![...] macro.
  2. Step 2: Check each option

    let prices = vec![7, 1, 5, 3, 6, 4]; uses vec![...], 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.
  3. Final Answer:

    let prices = vec![7, 1, 5, 3, 6, 4]; -> Option B
  4. Quick Check:

    Vector = vec![...] syntax [OK]
Hint: Use vec![] to create vectors in Rust [OK]
Common Mistakes:
  • Using array syntax instead of vector
  • Using tuple instead of vector
  • Invalid curly braces for initialization
3. What is the output of the following Rust code that solves the 'Best Time to Buy and Sell Stock I' problem?
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));
}
medium
A. 7
B. 6
C. 4
D. 5

Solution

  1. 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=5
  2. Step 2: Return max_profit

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

    5 -> Option D
  4. Quick Check:

    Max profit = 5 [OK]
Hint: Track min price and update max profit on each day [OK]
Common Mistakes:
  • Not updating min_price correctly
  • Calculating profit before updating min_price
  • Confusing max profit with max price
4. Identify the bug in this Rust function intended to solve the 'Best Time to Buy and Sell Stock II' (multiple transactions allowed):
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
}
medium
A. Index out of bounds error when i = 0
B. Profit calculation is incorrect for multiple transactions
C. Loop should start from 1 instead of 0
D. Prices vector should be mutable

Solution

  1. 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.
  2. Step 2: Identify fix

    Loop should start from i=1 to avoid negative index access.
  3. Final Answer:

    Index out of bounds error when i = 0 -> Option A
  4. Quick Check:

    Negative index access causes runtime error [OK]
Hint: Start loop from 1 to avoid negative index [OK]
Common Mistakes:
  • Starting loop at 0 causing invalid index
  • Not checking vector length before access
  • Assuming negative indices are valid
5. Given the stock prices [3, 3, 5, 0, 0, 3, 1, 4], what is the maximum profit achievable with at most two transactions (buy-sell pairs)?
hard
A. 5
B. 7
C. 6
D. 8

Solution

  1. Step 1: Understand two transactions limit

    We can buy and sell at most twice to maximize profit.
  2. 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 = 6
  3. Final Answer:

    6 -> Option C
  4. Quick Check:

    Sum of two best profits = 6 [OK]
Hint: Split array, find max profit left and right, sum max two [OK]
Common Mistakes:
  • Counting overlapping transactions
  • Choosing wrong buy/sell days
  • Ignoring the two transactions limit
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