Java Max Counters
public class Solution {
public static int[] maxCounters(int n, int[] a) {
int[] counters = new int[n];
int maxCounter = 0;
int lastUpdate = 0;
int condition = n + 1;
for (int v : a) {
if (v <= n) {
int index = v - 1;
if (counters[index] < lastUpdate) {
counters[index] = lastUpdate;
}
counters[index]++;
maxCounter = Math.max(counters[index], maxCounter);
}
if (v == condition) {
lastUpdate = maxCounter;
}
}
for (int k = 0; k < counters.length; k++) {
if (counters[k] < 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.