Go Max Counters
func maxCounters(n int, a []int) []int {
counters := make([]int, n)
maxCounter := 0
lastUpdate := 0
condition := n + 1
for _, v := range a {
if v <= n {
index := v - 1
if counters[index] < lastUpdate {
counters[index] = lastUpdate // should already be maxed
}
counters[index]++
if counters[index] > maxCounter {
maxCounter = counters[index]
}
}
if v == condition {
lastUpdate = maxCounter
}
}
// apply all max operations to avoid O(M*N) complexity
for k, v := range counters {
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.