Maxcounters in JavaScript
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.