Codility: Maxed Counters Problem


You are given N counters, initially set to 0, and you have two possible operations on them:

> -   _increase(X)_  − counter X is increased by 1,
> -   _max counter_  − all counters are set to the maximum value of any counter.

A non-empty array A of M integers is given. This array represents consecutive operations:

> -   if A[K] = X, such that 1 ≤ X ≤ N, then operation K is increase(X),
> -   if A[K] = N + 1 then operation K is max counter.


# you can write to stdout for debugging purposes, e.g.
# print("this is a debug message")

def solution(N, A):
    # write your code in Python 3.6
    C = [0]*N
    cur_max = 0
    maxed = False
    last_max = 0
    for c in A:
        index = c - 1
        if c <= N:
            if maxed and (C[index] < last_max):
                C[index] = last_max

            C[index] += 1
            if C[index] > cur_max:
                cur_max = C[index]
            # print("incr", C)    

        if c == (N + 1):
            maxed = True
            last_max = cur_max
            # print("max", C)
    index = 0
    for c in C:
        if last_max > C[index]: 
            C[index] = last_max 
        index += 1

    return C


Written with StackEdit.


A voyager on the journey to technology and art of software development. Pursuing arts, music, photography, and ways to live life on the edge

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.