PHP Max Counters
function maxCounters(int $n, array $a): array
{
$counters = array_fill(0, $n, 0);
$maxCounter = 0;
$lastUpdate = 0;
$condition = $n + 1;
foreach ($a as $v) {
if ($v <= $n) {
$index = $v - 1;
if ($counters[$index] < $lastUpdate) {
$counters[$index] = $lastUpdate; // should already be maxed
}
$counters[$index]++;
$maxCounter = $counters[$index] > $maxCounter ? $counters[$index] : $maxCounter;
}
if ($v === $condition) {
$lastUpdate = $maxCounter;
}
}
// apply all max operations to avoid O(M*N) complexity
foreach ($counters as $k => $v) {
if ($v < $lastUpdate) {
$counters[$k] = $lastUpdate;
}
}
return $counters;
}
This delays the expensive “set all counters to max” work until it is really needed, which keeps the solution fast.