MaxCounters

100% Correctness, but 80% efficient.

by sweetcoco

HTML

<h1>MaxCounters</h1>

<div id="brinza-task-description">
<p>You are given N counters, initially set to 0, and you have two possible operations on them:</p>
<blockquote><ul style="margin: 10px;padding: 0px;"><li><i>increase(X)</i> − counter X is increased by 1,</li>
<li><i>max counter</i> − all counters are set to the maximum value of any counter.</li>
</ul>
</blockquote><p>A non-empty zero-indexed array A of M integers is given. This array represents consecutive operations:</p>
<blockquote><ul style="margin: 10px;padding: 0px;"><li>if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),</li>
<li>if A[K] = N + 1 then operation K is max counter.</li>
</ul>
</blockquote><p>For example, given integer N = 5 and array A such that:</p>
<p></p><pre><tt>    A[0] = 3
    A[1] = 4
    A[2] = 4
    A[3] = 6
    A[4] = 1
    A[5] = 4
    A[6] = 4</tt></pre>
<p>the values of the counters after each consecutive operation will be:</p>
<p></p><pre><tt>    (0, 0, 1, 0, 0)
    (0, 0, 1, 1, 0)
    (0, 0, 1, 2, 0)
    (2, 2, 2, 2, 2)
    (3, 2, 2, 2, 2)
    (3, 2, 2, 3, 2)
    (3, 2, 2, 4, 2)</tt></pre>
<p>The goal is to calculate the value of every counter after all operations.</p>
<blockquote><p class="lang-c" style="font-family: monospace; font-size: 9pt; display: none"><tt>
struct&nbsp;Results&nbsp;{<br>
&nbsp;&nbsp;int&nbsp;*&nbsp;C;<br>
&nbsp;&nbsp;int&nbsp;L;<br>
};
</tt></p></blockquote>
<blockquote><p class="lang-pas" style="font-family: monospace; font-size: 9pt; display: none"><tt>
Results&nbsp;=&nbsp;record<br>
&nbsp;&nbsp;&nbsp;&nbsp;C&nbsp;:&nbsp;array&nbsp;of&nbsp;longint;<br>
&nbsp;&nbsp;&nbsp;&nbsp;L&nbsp;:&nbsp;longint;<br>
&nbsp;&nbsp;end;
</tt></p></blockquote>
<p>Write a function:</p>
<blockquote><p class="lang-c" style="font-family: monospace; font-size: 9pt; display: none"><tt>
struct Results solution(int N, int A[], int M);
</tt></p></blockquote>
<blockquote><p class="lang-cpp" style="font-family: monospace; font-size: 9pt; display:...

JavaScript

A = [3, 4, 4, 6, 1, 4, 4];
N = 5;

function solution(N, A) {
    // write your code in JavaScript (Node.js 0.12)
    
    var highest = 0,
        final = [];
    
    for (var i = 1; i <= N; i++) {
        final.push(0);
    }
    final.push(0);
    
    for (var j = 0; j < A.length; j++) {
        if (A[j] === N + 1) {
            for (var t = 0; t < final.length; t++) {
                final[t] = highest;
                continue;
            }
            } else {
            final[A[j]] += 1;
            if (final[A[j]] > highest) {
                highest = final[A[j]];
            }
        }
    }
    
    final.shift();
  
        return final;
}

console.log(solution(N, A));