Algorithm: Max Counters

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

    Let's see...

    public int[] Solution(int N, int[] A)
    {
        int[] data = new int[N];
        int maxval = 0;
        int baseval = 0;
        for (int K = 0; K < A.length; K++)
        {
            int index = A[K] - 1;
            if (index < 0 || index > N)
                throw new InvalidOperationException();
    
            if (index < N)
                maxval = baseval + Math.Max(maxval, ++data[index]);
            else
            {
                baseval = maxval;
                data = new int[N];
            }
        }
    
        for (int K = 0; K < N; K++)
            data[K] += baseval;
    
        return data;
    }
    

    I think that's O(N+K). Depends on how you count the Order of re-initializing the array.

提交回复
热议问题