fn max_distance(arr: &[i32]) -> usize {
use std::collections::HashMap;
let mut index_map = HashMap::new();
let mut max_dist = 0;
for (i, &num) in arr.iter().enumerate() {
if let Some(&first_index) = index_map.get(&num) {
let dist = i - first_index;
if dist > max_dist {
max_dist = dist;
}
} else {
index_map.insert(num, i);
}
}
max_dist
}
fn main() {
let arr = [7, 1, 4, 3, 1, 5, 3, 4, 9, 1, 3];
println!(
"Maximum distance between two occurrences of the same number: {}",
max_distance(&arr)
);
}
/*
run:
Maximum distance between two occurrences of the same number: 8
*/