Rust Max Counters
fn max_counters(n: i64, a: &[i64]) -> Vec<i64> {
let mut counters = vec![0i64; n as usize];
let mut max_counter = 0i64;
let mut last_update = 0i64;
let condition = n + 1;
for &v in a {
if v <= n {
let index = (v - 1) as usize;
if counters[index] < last_update {
counters[index] = last_update;
}
counters[index] += 1;
max_counter = max_counter.max(counters[index]);
}
if v == condition {
last_update = max_counter;
}
}
for c in counters.iter_mut() {
if *c < last_update {
*c = last_update;
}
}
counters
}
This delays the expensive “set all counters to max” work until it is really needed, which keeps the solution fast.