# Codility Max Counters 100% Javascript Solution

Ok the Max Counters problem is the first algo challenge marked as medium in the codility lessons.

I devised a O(m+n) solution.

We first check if there’s no element N+1 in the array we just run the through the array and increment the counters at the end.

For the case when N+1 is present in the array, we run through the array increasing the counters while A[K] = X < N+1. We keep in the variable max the maximum available counter for the moment when we will have to update all.

When N+1 is met we update all counters to the max value. If the next element is again N+1 we just continue the iteration, as we don’t have a new counter to update since there was no incrementation since the last update.

## The Javascript Solution:

``````function solution(N, A) {
let  counters = Array (N).fill(0)
//take care of the case when there is no element === N+1
//simply run through the array and return the counters at the end
if (A.indexOf(N+1) === -1){
for (let j = 0; j < A.length; j++){
counters[A[j]-1]++
}
return counters
}

let max = min = maxSum = 0
let nextSkip = 0

for (let i = 0; i < A.length; i ++){
if (A[i] < N + 1){
nextSkip = 0
counters[A[i]-1]++
//we check and keep a record of the max counter
if (counters[A[i]-1] > max) {
max = counters[A[i]-1]
}
} else if (A[i] === N + 1 && nextSkip === 0){
nextSkip = 1
for (let j =0; j < counters.length; j++){
counters[j] = max
}
}
}
return counters

}``````

Here is the report.

Did you find a better solution? Let me know in the comments!