maximum difference in list of numbers
// As old-style iterative
fn max_diff2(numbers: &[i32]) -> i32 {
if numbers.len() < 2 { return 0 }
let mut min = numbers[0];
let mut max = numbers[0];
for n in numbers {
if n > &max {
max = *n;
}
if n < &min {
min = *n;
}
}
max - min
}
// As one-liner
fn max_diff(numbers: &[i32]) -> i32 {
*numbers.iter().max().unwrap_or(&0) - *numbers.iter().min().unwrap_or(&0)
}
fn main() {
println!("Max diff = {} ",max_diff(&[0, 1, 2, 3, 4, 5, 6]) ); //, 6););
println!("Max diff = {} ",max_diff(&[7,7,-7,7,7,7,7,7,7,7,7]) );
}