Maxcounters in JavaScript 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 &lt;= 0) {
        return -1;
    }

    // set counters to 0
    for (let i = 0; i &lt; N; i++) {
        counters[i] = 0;
    }

    for (let K = 0; K &lt; M; K += 1) {
        if (A[K] === N + 1) {
            // set counters to last maximum
            for (let j = 0; j &lt; N; j++) {
                counters[j] = max;
            }
        } else if (A[K] &gt; 0 &amp;&amp; A[K] &lt;= N) {
            // add one to counter
            counters[A[K] - 1] = counters[A[K] - 1] + 1;
            // update maximum
            if (counters[A[K] - 1] &gt; max) {
                max = counters[A[K] - 1];
            }
        }
    }

    return counters;
}
You can save some time by not running through every counter and setting them to the maximum each time max gets called. Since they are all equivalent at the start and after each time the max is called, you can just record the current maximum counter value (in between each call of max) and add it all together at the end, rather than updating every counter element each time max is called.

let currentTally = {};
let currentMax = 0;
let total = 0;
for (let K = 0; K &lt; M; K += 1) {
        if (A[K] &lt;= N) {
             if(currentTally[A[K]]){
                 currentTally[A[K]] += 1;
             }else {
                 currentTally[A[K]] = 1;
             }
             if( currentTally[A[K]] &gt; currentMax) {
                  currentMax = currentTally[A[K]];
             }
        }

        if (A[K] === N + 1) {
            total += currentMax;
            currentTally = {};
            currentMax = 0;
        } 
        }
    }
    for(let i = 0; i &lt; counters.length; i++) {
         if(currentTally[i]){
             counters[i] = total + currentTally[i];
         }else{
             counters[i] = total;
         }
    }


Also, this way, no need to set all counters to zero in the first place.