Algorithm: Max Counters

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

    Same principle as everybody scoring 100% really, it is just that I find this version easier to read (and it is probably only because I wrote it).

    using System;
    using System.Linq;
    
    class Solution 
    {
        public int[] solution(int N, int[] A) 
        {
    
            var currentMax = 0;
            var resetValue = 0;
            var counters = Enumerable.Range(1, N).ToDictionary(i => i, i => 0);
    
            foreach (var a in A)
            {
                if (a == N + 1) resetValue = currentMax;
                else
                {
                    counters[a] = Math.Max(counters[a], resetValue) + 1;
                    currentMax = Math.Max(currentMax, counters[a]);
                }
            }
            return counters.Values.Select(v => Math.Max(v,resetValue)).ToArray();
        }
    }
    

提交回复
热议问题