Algorithm: Max Counters

后端 未结 22 1602
孤城傲影
孤城傲影 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:38

    Here is the kotlin version, 100% on codility

    fun solutionMissingInteger(N: Int, A: IntArray): IntArray {
        val counters = IntArray(N)
        var max = 0
        var lastUpdate = 0
        for (index in A.indices) {
            val element = A[index]
            if (element == N + 1) {
                lastUpdate = max
            } else {
                val position = element - 1
                if (counters[position] < lastUpdate) {
                    counters[position] = lastUpdate + 1
                } else {
                    counters[position] = counters[position] +1
                }
    
                if (counters[position] > max) {
                    max = counters[position]
                }
            }
        }
        setAllCountersToMaxValue(lastUpdate, counters)
        return counters
    }
    
    private fun setAllCountersToMaxValue(lastUpdate: Int, counters: IntArray) {
        for (index in counters.indices) {
            if (counters[index] < lastUpdate)
                counters[index] = lastUpdate
        }
    }
    

提交回复
热议问题