Read the problem before touching the keyboard
Most failed coding rounds fail in the first two minutes: the candidate starts typing a solution to a problem they have not fully read. Slow down and write these five things down (in a comment, on the whiteboard, or out loud) before any code. In Rust the second step matters more than in most languages, because the types you pick decide what the compiler will let you do.
- 1Restate it
One sentence, in your own words. "Given a list of prices, return the biggest profit from one buy followed by one sell."
- 2Inputs and outputs, as Rust types
Take a slice,
&[u32], not aVec: the function only reads it, and a slice accepts arrays and vectors alike. Can there be no answer? Then returnOption<T>, not a magic-1. - 3Constraints
How big is n? Can values be negative (
i32) or not (u32,usize)? Can a sum overflowi32? Duplicates? Sorted? These decide the algorithm and the integer type. - 4Two examples by hand
One normal, one tricky. Work them out on paper. If you cannot do it by hand, you cannot code it.
- 5Edge cases
Empty input, one element, all equal, already sorted, and anything that makes a
usizesubtraction go below zero.
// Restated: best profit from one buy then one later sell; 0 if prices only fall.
// Input: a slice of prices (may be empty). Output: u32, never negative.
fn max_profit(prices: &[u32]) -> u32 {
let mut lowest = u32::MAX;
let mut best = 0;
for &price in prices {
lowest = lowest.min(price); // cheapest buy so far
best = best.max(price - lowest); // sell today? (price >= lowest, so no underflow)
}
best
}
fn main() {
println!("{}", max_profit(&[7, 1, 5, 3, 6, 4])); // normal: buy 1, sell 6
println!("{}", max_profit(&[7, 6, 4, 3, 1])); // only falls
println!("{}", max_profit(&[])); // empty
println!("{}", max_profit(&[5])); // one day
}5
0
0
0The comments at the top are the reading step. The four calls in main are the examples and edge cases from that step, not an afterthought.
Change the function to return Option<(usize, usize)>: the buy day and sell day, or None when no profit is possible. Which of the four calls now print None?
