-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path09 MaxCounters
42 lines (31 loc) · 1.24 KB
/
09 MaxCounters
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/*
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 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.
*/
/*-----------------------------------------------------*/
// you can write to stdout for debugging purposes, e.g.
// console.log('this is a debug message');
function solution(N, A) {
// write your code in JavaScript (Node.js 8.9.4)
let acum = 0;
let countersArray = new Array(N).fill(0);
let max = 0;
for (let i=0; i<A.length; i+=1) {
if (A[i] < N+1){
let incrIndex = A[i]-1;
if (countersArray[incrIndex] < max) countersArray[incrIndex] = max;
countersArray[incrIndex]+=1;
if (acum < countersArray[incrIndex]) acum = countersArray[incrIndex];
} else {
max = acum;
}
}
for(let i=0; i<N; i+=1) {
if (countersArray[i] < max) countersArray[i] = max;
}
return countersArray;
}