Algorithm: Max Counters

后端 未结 22 1621
孤城傲影
孤城傲影 2021-02-04 07:40

I have the following problem:

You are given N counters, initially set to 0, and you have two possible operations on them:

  • increase(X) − counter X is increa
22条回答
  •  粉色の甜心
    2021-02-04 08:17

    Here is Scala version, 100% on codility:

    import java.util
    
    def solution(N: Int, A: Array[Int]): Array[Int] = {
    
        var counters = new Array[Int](N)
    
        var maxCounter = 0
    
        for(ind <- 0 to A.length-1){
    
    
          if(A(ind) == (N+1)){
    
            //all to max
            util.Arrays.fill(counters,maxCounter)
    
          }else{
            //ind -1  cause array index start with 0 which is marked as 1 in the input data
            counters(A(ind)-1) += 1
    
            //update max counter if necessary
            if(maxCounter< (counters(A(ind)-1))) maxCounter = (counters(A(ind)-1))
    
          }
    
        }
    
        return counters
      }
    

    Performance: https://codility.com/demo/results/trainingKJT6Y3-74G/

提交回复
热议问题