MaxCounters Codility JAVA solution (100/100)

Ok, this is first interesting one. The concept goes like this.

We iterate through input array and increase a value for element in counterArray. Elements in counterArray represents number of repetitions in inputArray of the value of index in counterArray. We intuitively iterate through inputArray until we get to element with value of N+1. Then reset all the fields in counterArray to zero and continue iterating. Every time we get to N+1 element we remember the value of biggest element in counterArray. After that loop we iterate through counterArray and increase every element by the biggest remembered element.

Now, this concept works fine but when we want to reset an array we hit the performance lag. At first I created zeroedArray and

Even tho, JAVA is supposed to be “pass by value” language, this way it passes a reference to the zeroedArray so changes to counterArray reflect to zeroedArray so it isn’t zeroed any more. 🙂

Second thing I tried was

This way everything worked fine but the code was too slow. I tried to optimise it but it was always around 11 seconds on big queries while the limit was 8.

So the best solution to copying an array to another array by value is to use

So here is the entire solution with 100/100 score.

 

 

  • Zvonimir Sabljić

    brija

  • Clubble App

    kuis