Skip to content

Instantly share code, notes, and snippets.

@jeanlescure
Last active September 18, 2015 11:49
Show Gist options
  • Save jeanlescure/13218a13567bc0b5259a to your computer and use it in GitHub Desktop.
Save jeanlescure/13218a13567bc0b5259a to your computer and use it in GitHub Desktop.
Codility MaxCounters Solution in Javascript - 66% score
/*
You are given N counters, initially set to 0, and you have two possible operations on them:
• increase(X) − counter X is increased by 1,
• max counter − all counters are set to the maximum value of any counter.
A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:
• if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
• if A[K] = N + 1 then operation K is max counter.
*/
var max;
function solution(N, A) {
var counters = Array.apply(null, Array(N)).map(function(){return 0;});
var NP = N + 1;
for (var K in A){
if (A[K] >= 1 && A[K] <= N){
counters[A[K] - 1]++;
}else if(A[K] === NP){
max = Math.max.apply(this, counters);
counters = counters.map(retMax);
}
}
return counters;
}
function retMax(){ return max; }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment