I am trying to solve this question: MaxCounters.
Solving it is straightforward, but solving it fast enough is proving very difficult. How can I improve the performance of this code? At the moment it is too slow for the large_random_2
and extreme_large
tests.
function solution(N, A) {
const M = A.length;
let max = 0;
let counters = new Array(N);
if (M <= 0) {
return -1;
}
// set counters to 0
for (let i = 0; i < N; i++) {
counters[i] = 0;
}
for (let K = 0; K < M; K += 1) {
if (A[K] === N + 1) {
// set counters to last maximum
for (let j = 0; j < N; j++) {
counters[j] = max;
}
} else if (A[K] > 0 && A[K] <= N) {
// add one to counter
counters[A[K] - 1] = counters[A[K] - 1] + 1;
// update maximum
if (counters[A[K] - 1] > max) {
max = counters[A[K] - 1];
}
}
}
return counters;
}