Algorithm: Max Counters

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

    ES6

    const solution = (n, a) => {
        // Initialize to zero
        let counter =  new Array(n);
        for(let i = 0  ; i < n ; i++ ){
            counter[i] = 0;
        }
        let max = 0;
        for(let j = 0  ; j < a.length ; j++ ){
            const item = a[j];
            if( item > n) {
                for(let i = 0  ; i < n ; i++ ){
                    counter[i] = max;
                }
            }
            else{
                counter[item-1]++; 
                if(max < counter[item-1])
                {
                    max = counter[item-1];
                }
            }
        }
        return counter;
    };
    

提交回复
热议问题