How to get the number of days needed to wait after a day (a[i]) gets warmer given a vector of temperatures in Rust

1 Answer

0 votes
// Print all elements in a vector
fn print_vec(arr: &Vec<i32>) {
    for n in arr {
        print!("{} ", n);
    }
    println!();
}

// Calculate how many days you must wait for a warmer temperature
fn number_of_days_to_wait(temperatures: &Vec<i32>) -> Vec<i32> {
    let size = temperatures.len();
    let mut result = vec![0; size];
    let mut stack: Vec<usize> = Vec::with_capacity(size); // stack of indices

    for i in 0..size {
        // While the current temperature is warmer than the temperature
        // at the index stored at the top of the stack:
        while let Some(&top_idx) = stack.last() {
            if temperatures[i] > temperatures[top_idx] {
                stack.pop();
                result[top_idx] = (i - top_idx) as i32;
            } else {
                break;
            }
        }

        // Push the current index onto the stack
        stack.push(i);
    }

    // Remaining indices in the stack have no warmer future day
    // (result already contains zeros)
    result
}

fn main() {
    let temperatures = vec![82, 84, 81, 58, 85, 89, 75, 71];

    // 82 -> 84 = 1
    // 84 -> 81 -> 58 -> 85 = 3
    // 81 -> 58 -> 85 = 2
    // 58 -> 85 = 1
    // 85 -> 89 = 1
    // 89 -> 75 -> 71 = 0
    // 75 -> 71 = 0

    let result = number_of_days_to_wait(&temperatures);

    print_vec(&result);
}



/*
run:

1 3 2 1 1 0 0 0 

*/

 



answered 14 hours ago by avibootz

Related questions

...