MaxCounters 100% Solution in Javascript

Question

app.codility.com

Solution

app.codility.com

function solution(N, A) {
    
    let setMax = 0;
    let knownMax = 0;
    let currentMax = 0;
    let count = [];
    
    for (let i = 0; i < N; i++) {
        count[i] = 0;
    }
    
    for (let i = 0; i < A.length; i++) {
        if (A[i] < N+1) { 
            if(setMax === 0 || count[A[i]-1] > currentMax) {
                count[A[i]-1]++;
            } else
                count[A[i]-1] = currentMax+1;
            knownMax = Math.max(knownMax, count[A[i]-1]);   // here
        }
        else {
            currentMax = knownMax;
            // console.log(currentMax);
            setMax = 1;
        }
        // console.log(count);
    }
    
    for (let i = 0; i < N; i++) {
        count[i] = Math.max(count[i], currentMax);
    }
    
    return count;
    
}

Note

  • Record the max we known after each acceleration