Algorithm: Max Counters

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

    This is what I came up with, but I am not sure if it works 100%:

    public int[] solution(int N, int[] A) {
        int[] result = new int[N];
        int maximum = 0;
        int resetLimit = 0;
    
        for (int K = 0; K < A.Length; K++)
        {
            if (A[K] < 1 || A[K] > N + 1)
                throw new InvalidOperationException();
    
            if (A[K] >= 1 && A[K] <= N)
            {
                if (result[A[K] - 1] < resetLimit) {
                    result[A[K] - 1] = resetLimit + 1;
                } else {
                    result[A[K] - 1]++;
                }
    
                if (result[A[K] - 1] > maximum)
                {
                    maximum = result[A[K] - 1];
                }
            }
            else
            {
                // inefficiency here
                //for (int i = 0; i < result.Length; i++)
                //    result[i] = maximum;
                resetLimit = maximum;
            }
        }
    
        for (int i = 0; i < result.Length; i++)
            result[i] = Math.Max(resetLimit, result[i]);
    
        return result;
    }
    

提交回复
热议问题