Algorithm: Max Counters

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

    A 100% JavaScript solution

    function solution(N, A) {
        // initialize all counters to 0
        let counters = Array(N).fill(0)
    
        // The maximum value of the counter is 0
        let max = 0
    
        // This variable will determine if an increment all operation has been encountered
        // and its value determines the maximum increment all operation encountered so far
        // for start it is 0, and we will set it to the value of max when A[i] == N + 1
        let max_all = 0
    
        for(let i = 0; i < A.length; i++) {
    
            if(A[i] <= counters.length) {
    
                // if the value of A[i] is 1, we have to increment c[0]
                // and hence the following index
                const c_index = A[i] - 1
    
                // if max all operation was found previously,
                // we have to set it here, because we are not setting anything in the else section
                // we are just setting a flag in the else section
                // if its value however is greater than max_all, it probably was already maxed
                // and later incremented, therefore we will skip it
                if(counters[c_index] < max_all) counters[c_index] = max_all
    
                // do the increment here
                const v = ++counters[c_index]
    
                // update the max if the current value is max
                max = v > max ? v : max
            }
    
            // this is straight forward
            else max_all = max
        }
    
        // if there are remaining items that have not been set to max_all inside the loop
        // we will update them here.
        // and we are updating them here instead of inside the for loop in the else section
        // to make the running time better. If updated inside the loop, we will have a running time of M * N
        // however here it's something like (M + N) ~ O(N)
        if(max_all) counters = counters.map(v => v < max_all ? max_all : v)
    
        // return the counters
        return counters
    }
    

提交回复
热议问题