Algorithm: Max Counters

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

    Rue, I just ran this locally. Watched the counters myself. I used this algorithm:

        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
                {
                    resetlimit = maximum;
                    result = Enumerable.Repeat(maximum, result.Length).ToArray();
                }
            }
    
            //for (int i = 0; i < result.Length; i++)
            //{
            //    result[i] = Math.Max(resetlimit, result[i]);
            //}
    
            return result;
        }
    }
    

    looking at the problem and the result sets, you must include in the inefficient for loop in the else statement. The for loop outside does not replicate the 2nd operation
    •if A[K] = N + 1 then operation K is max_counter.

    In order for iteration A[3] = 6 to set result[] all to '2' you must load the result array with the maximum counter. Otherwise your return will never have (2,2,2,2,2) as the 4th example array shows.

    I too must take a test to get my dream job so the little inefficiency here is important;

    the statement

      result = Enumerable.Repeat(maximum, result.Length).ToArray();
    

    loads the array all in one shot so no inner loop and no inner efficiency. I think that is pretty close to the correct result sets. I'm surprised they didn't ask to return like a jagged array of the total return. Still, this codility test scares me a lot.

提交回复
热议问题