📖 Scenario: You are helping a friend who wants to understand how to find the best time to buy and sell stocks to maximize profit. They have a list of daily stock prices and want to learn how to find the best single buy-sell pair.
🎯 Goal: Build a Rust program that finds the maximum profit from buying and selling a stock once, given a list of daily prices.
📋 What You'll Learn
Create a vector called prices with the exact values [7, 1, 5, 3, 6, 4]
Create a variable called min_price and set it to the first price in prices
Use a for loop with variable price to iterate over prices starting from the second element
Inside the loop, update min_price if price is lower
Inside the loop, calculate profit as price - min_price and update max_profit if profit is higher
Print the max_profit at the end
💡 Why This Matters
🌍 Real World
This project helps understand how to analyze stock price data to make smart buy and sell decisions for profit.
💼 Career
Knowing how to process and analyze data with loops and conditions is essential for software developers working with financial or time-series data.
Progress0 / 4 steps
1
Create the stock prices vector
Create a vector called prices with these exact values: [7, 1, 5, 3, 6, 4]
DSA Rust
Hint
Use let prices = vec![7, 1, 5, 3, 6, 4]; to create the vector.
2
Set up minimum price and maximum profit variables
Create a variable called min_price and set it to the first element of prices. Also create a variable called max_profit and set it to 0.
DSA Rust
Hint
Use let mut min_price = prices[0]; and let mut max_profit = 0;.
3
Loop through prices to find max profit
Use a for loop with variable price to iterate over prices[1..]. Inside the loop, update min_price if price is less than min_price. Calculate profit as price - min_price and update max_profit if profit is greater.
DSA Rust
Hint
Use a for loop over &prices[1..]. Use *price to get the value. Update min_price and max_profit accordingly.
4
Print the maximum profit
Print the value of max_profit using println!.
DSA Rust
Hint
Use println!("{}", max_profit); to print the result.
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
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 A
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
Step 1: Identify Rust vector syntax
In Rust, vectors are created using vec![...] macro.
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.
Final Answer:
let prices = vec![7, 1, 5, 3, 6, 4]; -> Option B
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
Step 1: Trace the loop to find min_price and max_profit