Warmer Days Wait On A Monotonic Stack

Keep unresolved indexes on a stack whose temperatures never increase, popping to settle wait distances the moment a warmer day appears.

RustData Integrity

Code

rustsnippet
28 lines
// 栈里保存还没等到更暖天的下标:温度沿栈单调不增
fn daily_temperatures(temps: &[i32]) -> Vec<usize> {
    let mut wait = vec![0usize; temps.len()];
    let mut stack: Vec<usize> = Vec::with_capacity(temps.len());
    for (i, &t) in temps.iter().enumerate() {
        // 当前更暖就结算栈顶:wait 等于下标差
        while let Some(&top) = stack.last() {
            if temps[top] >= t {
                break;
            }
            stack.pop();
            wait[top] = i - top;
        }
        stack.push(i);
    }
    wait
}

fn main() {
    let answer = daily_temperatures(&[73, 74, 75, 71, 69, 72, 76, 73]);
    println!("{answer:?}");

    let flat = daily_temperatures(&[30, 30, 31]);
    println!("{flat:?}");

    let cooling = daily_temperatures(&[40, 39, 38]);
    println!("{cooling:?}");
}

How it works

The moving parts sit in the functions daily_temperatures and main.

Iteration happens inside for (i, &t) in temps.iter().enumerate() — everything outside it runs once.

What to watch for

  • Imports, where present, target standard-library modules only.

Putting it to use

Entry signature: fn daily_temperatures(temps: &[i32]) -> Vec<usize>

main sequences daily_temperatures; executing the file runs that flow once.

Core lines

while let Some(&top) = stack.last() {
    if temps[top] >= t {
        break;
    }
    stack.pop();
    wait[top] = i - top;
}

Interactive Tools for This Topic

FAQ

How do you run Warmer Days Wait On A Monotonic Stack?
The runtime alone is enough: execute the file as a complete program.