Algorithm: Max Counters

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

    Here's a solution I came up with in Python (100/100 on codility); it's a little different than others I've seen on here so thought I'd share:

    def solution(N, A):
        count = [0] * N
        max_counter = [i for i, a in enumerate(A) if a == N+1]
        if len(max_counter) == len(A):
            return count
        if max_counter:
            mode = 0
            for i, m in enumerate(max_counter):
                if m == 0 or m - max_counter[i-1] == 1:
                    continue
                subcount = {}
                if i == 0:
                    for k in A[:m]:
                        if k not in subcount:
                            subcount[k] = 1
                        else:
                            subcount[k] += 1
                else:
                    for k in A[max_counter[i-1]+1:m]:
                        if k not in subcount:
                            subcount[k] = 1
                        else:
                            subcount[k] += 1
                mode += max(subcount.values())
            count = [mode] * N
            for k in A[max_counter[-1]+1:]:
                count[k-1] += 1
        else:
            for k in A:
                count[k-1] += 1
        return count
    

提交回复
热议问题