Algorithm: Max Counters

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

    public int[] counters(int N, int[] A)
    {
        int[] count = new int[N];
        int maxCount = 0;
        int setAll = 0;
    
        for (int i = 0; i < A.Length; i++)
        {
            if (A[i] == N + 1)
            {
                setAll += maxCount;
                maxCount = 0;
                count = new int[N];
            }
            else
            {
                count[A[i] - 1] += 1;
    
    
                if (count[A[i] - 1] > maxCount)
                {
                    maxCount = count[A[i] - 1];
                }
            }
        }
    
        for (int j = 0; j < count.Length; j++)
        {
            count[j] += setAll;
        }
    
        return count;
    }
    

    I think this is O(N+K), but codility say its O(N*K)? Would appreciate if anyone could explain which is correct...

提交回复
热议问题