Bird
Raised Fist0
DSA Rustprogramming~20 mins

Buy and Sell Stocks All Variants in DSA Rust - Practice Problems & Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Stock Trading Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust code for max profit with one transaction?
Given the prices array, what is the maximum profit from a single buy-sell transaction?
DSA Rust
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));
}
A7
B5
C4
D6
Attempts:
2 left
💡 Hint
Track the lowest price and calculate profit at each step.
❓ Predict Output
intermediate
2:00remaining
What is the output of this Rust code for max profit with unlimited transactions?
Given the prices array, what is the maximum profit from unlimited buy-sell transactions?
DSA Rust
fn max_profit(prices: Vec<i32>) -> i32 {
    let mut profit = 0;
    for i in 1..prices.len() {
        if prices[i] > prices[i - 1] {
            profit += prices[i] - prices[i - 1];
        }
    }
    profit
}

fn main() {
    let prices = vec![7,1,5,3,6,4];
    println!("{}", max_profit(prices));
}
A6
B8
C5
D7
Attempts:
2 left
💡 Hint
Sum all positive differences between consecutive days.
❓ Predict Output
advanced
2:30remaining
What is the output of this Rust code for max profit with at most two transactions?
Given the prices array, what is the maximum profit with at most two buy-sell transactions?
DSA Rust
fn max_profit_two_transactions(prices: Vec<i32>) -> i32 {
    let n = prices.len();
    if n == 0 { return 0; }
    let mut left_profits = vec![0; n];
    let mut right_profits = vec![0; n + 1];

    let mut min_price = prices[0];
    for i in 1..n {
        min_price = min_price.min(prices[i]);
        left_profits[i] = left_profits[i - 1].max(prices[i] - min_price);
    }

    let mut max_price = prices[n - 1];
    for i in (0..n).rev() {
        max_price = max_price.max(prices[i]);
        right_profits[i] = right_profits[i + 1].max(max_price - prices[i]);
    }

    let mut max_profit = 0;
    for i in 0..n {
        max_profit = max_profit.max(left_profits[i] + right_profits[i + 1]);
    }
    max_profit
}

fn main() {
    let prices = vec![3,3,5,0,0,3,1,4];
    println!("{}", max_profit_two_transactions(prices));
}
A6
B7
C8
D5
Attempts:
2 left
💡 Hint
Use two passes: left to right and right to left profits.
❓ Predict Output
advanced
2:30remaining
What is the output of this Rust code for max profit with cooldown period?
Given the prices array, what is the maximum profit with cooldown (one day after selling cannot buy)?
DSA Rust
fn max_profit_with_cooldown(prices: Vec<i32>) -> i32 {
    let n = prices.len();
    if n == 0 { return 0; }
    let mut hold = vec![0; n];
    let mut sold = vec![0; n];
    let mut rest = vec![0; n];

    hold[0] = -prices[0];
    sold[0] = 0;
    rest[0] = 0;

    for i in 1..n {
        hold[i] = hold[i - 1].max(rest[i - 1] - prices[i]);
        sold[i] = hold[i - 1] + prices[i];
        rest[i] = rest[i - 1].max(sold[i - 1]);
    }

    sold[n - 1].max(rest[n - 1])
}

fn main() {
    let prices = vec![1,2,3,0,2];
    println!("{}", max_profit_with_cooldown(prices));
}
A3
B4
C2
D5
Attempts:
2 left
💡 Hint
Track hold, sold, and rest states for each day.
❓ Predict Output
expert
3:00remaining
What is the output of this Rust code for max profit with transaction fee?
Given the prices array and fee, what is the maximum profit with unlimited transactions and fee per transaction?
DSA Rust
fn max_profit_with_fee(prices: Vec<i32>, fee: i32) -> i32 {
    let n = prices.len();
    if n == 0 { return 0; }
    let mut cash = 0;
    let mut hold = -prices[0];

    for i in 1..n {
        cash = cash.max(hold + prices[i] - fee);
        hold = hold.max(cash - prices[i]);
    }
    cash
}

fn main() {
    let prices = vec![1,3,2,8,4,9];
    let fee = 2;
    println!("{}", max_profit_with_fee(prices, fee));
}
A5
B6
C8
D7
Attempts:
2 left
💡 Hint
Track cash and hold states, subtract fee on sell.

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