Skip to content

Instantly share code, notes, and snippets.

@MichaelWalker-git
Created October 21, 2016 14:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MichaelWalker-git/d044a9646a1ad764a53317b0c6a16bf0 to your computer and use it in GitHub Desktop.
Save MichaelWalker-git/d044a9646a1ad764a53317b0c6a16bf0 to your computer and use it in GitHub Desktop.
/*
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.
Write a function that, given an integer N and a non-empty zero-indexed array A consisting of M integers,
returns a sequence of integers representing the values of the counters.
*/
function solution(N, A) {
var j;
var i;
var len = A.length;
var lastMax = 0;
var max = 0;
var results = new Array (N);
for(j = 0; j < N; j++) results[j] = 0;
//Sets all of the preliminary array elements to 0
var n1 = N + 1;
//adds the number of Counters to N+1
for(j=0; j < len; j++){
//Option 1: where current number is less than counter max
if(A[j] < n1){
// i = value -1
i = A[j] - 1;
//sets the empty result counters to last max
if (results[i] < lastMax){
results[i] = lastMax;
}
results[i]++;
//resets the max
if (max < results[i]){
max = results[i];
}
//Option 2: Current number is greater than counter max (N+1)
} else {
lastMax = max;
}
}
//lastMax is a 3rd party variable that sets the lastMax
for(j = 0; j < N; j++){
if (results[j] < lastMax) results[j] = lastMax;
}
return results;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment