
Let’s dive into the classic best time to buy and sell stock problems using Rust. I want to share the code first, then it will break down the line by line in a way that is easy to follow – whether you are new in the war or just brush. After that, we will run through examples, discover large rust concepts and wrapped up with time and space complexity.
Table of Contents
Leetcode Problem 121. Best Time to Buy and Sell Stock
You are given an array prices
where prices[i]
is the price of a given stock on the ith
day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0
.
The Rust Code Solution
Here’s the solution in all its glory:
rust
impl Solution {
pub fn max_profit(prices: Vec<i32>) -> i32 {
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);
}
max_profit
}
}
Simple, right? Don’t worry if it looks a bit cryptic at first—I’ll explain every piece.
Breaking It Down, Line by Line
1. impl Solution {
Rust uses impl to say, “Hey, I’m about to define some behavior for this thing called Solution.” Here, Solution is a struct that LeetCode provides in its Rust template.
Think of this line as setting up a toolbox where we’ll stash our max_profit function.
2. pub fn max_profit(prices: Vec<i32>) -> i32 {
- pub means “public”—this function is available for the outside world (like LeetCode’s test runner) to call.
- fn is Rust’s way of saying “function incoming!”
- max_profit is the name of our function.
- prices: Vec<i32> tells us we’re taking a vector (a growable list) of 32-bit integers (i32) as input. These are the stock prices for each day.
- -> i32 means we’re promising to return a 32-bit integer—the maximum profit we can make.
This line is like the front door to our solution—it defines what we’re working with and what we’ll give back.
3. let mut min_price = i32::MAX;
Here, we create a variable called min_price to track the lowest stock price we’ve seen so far.
- let declares the variable.
- mut means it’s mutable—we can change it later (and we will!).
- i32::MAX is a big number (2,147,483,647, to be exact), the largest value an i32 can hold. We start with this so the first price we see will always be smaller.
Think of min_price as our “best deal” tracker—it’s going to keep dropping as we find cheaper prices.
4. let mut max_profit = 0;
Next up is max_profit, which holds the biggest profit we can make. We set it to 0 to start because, worst case, we make no profit at all (if prices just keep dropping). Like min_price, it’s mutable because we’ll update it as we go.
5. for price in prices {
This is where the action happens. The for loop steps through each price in the prices vector, one by one. It’s like flipping through a list of daily stock prices to see what we can do with them.
6. min_price = min_price.min(price);
Inside the loop, we update min_price. The .min(price) method compares min_price to the current price and picks the smaller one. So, if today’s price is cheaper than our previous best deal, min_price gets updated. This ensures we always know the lowest price we could’ve bought at up to this point.
7. max_profit = max_profit.max(price – min_price);
Now, we calculate the profit we could make if we sold at the current price after buying at min_price (that’s price – min_price). The .max() method compares this potential profit to our current max_profit and keeps the larger value. This way, max_profit always reflects the best opportunity we’ve found so far.
8. } (End of the loop)
The loop keeps running until we’ve checked every price in the list, constantly refining min_price and max_profit.
9. max_profit
Finally, we return max_profit. In Rust, the last expression in a function is the return value—no return keyword needed (though you could write return max_profit; if you prefer). This is the maximum profit we could’ve made with one buy and one sell.
Key Rust Concepts in Play
Here’s a quick rundown of the Rust terms and tricks we used:
Term | What It Does |
---|---|
impl | Sets up a block to define methods for a struct (like Solution). |
pub | Makes our function callable from outside the struct. |
fn | Declares a function—pretty straightforward! |
Vec<i32> | A dynamic array (vector) of 32-bit integers (i32). |
-> i32 | Says “this function returns an i32.” |
let | Creates a new variable. |
mut | Lets us modify a variable after creating it. |
i32::MAX | The biggest i32 possible—our starting point for min_price. |
for … in | Loops over a collection, like our prices vector. |
.min(x) | Picks the smaller of two values. |
.max(x) | Picks the larger of two values. |
Let’s See It in Action
Example 1: prices = [7, 1, 5, 3, 6, 4]
Let’s walk through this step by step:
Day (Price) | min_price | price – min_price | max_profit |
---|---|---|---|
7 | 7 | 0 | 0 |
1 | 1 | 0 | 0 |
5 | 1 | 4 | 4 |
3 | 1 | 2 | 4 |
6 | 1 | 5 | 5 |
4 | 1 | 3 | 5 |
- Start with min_price at i32::MAX, but it drops to 7, then 1.
- When we hit 5, we could make 4 profit (5 – 1), so max_profit becomes 4.
- At 6, profit jumps to 5 (6 – 1), and max_profit updates to 5.
- Final result: 5 (buy at 1, sell at 6).
Example 2: prices = [7, 6, 4, 3, 1]
Now a trickier one:
Day (Price) | min_price | price – min_price | max_profit |
---|---|---|---|
7 | 7 | 0 | 0 |
6 | 6 | 0 | 0 |
4 | 4 | 0 | 0 |
3 | 3 | 0 | 0 |
1 | 1 | 0 | 0 |
- Prices just keep dropping—no chance to profit here.
- max_profit stays at 0 because we can’t sell higher than we buy.
Time and Space Complexity
- Time Complexity: O(n)
We only loop through the prices once—nice and efficient. - Space Complexity: O(1)
Just two variables (min_price and max_profit), no matter how big the input gets.
Wrapping Up
This solution is slick and to the point:
- It’s a single-pass approach, scanning the prices once.
- min_price keeps track of the cheapest buy point so far.
- max_profit captures the best profit we can snag.
- It even handles cases where no profit is possible (returning 0).