알고리즘/codility

Lesson 4 Counting Elements MaxCounters 나만의풀이

친구들안녕 2021. 5. 31. 01:20

문제

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.

For example, given integer N = 5 and array A such that:

A[0] = 3 A[1] = 4 A[2] = 4 A[3] = 6 A[4] = 1 A[5] = 4 A[6] = 4

the values of the counters after each consecutive operation will be:

(0, 0, 1, 0, 0) (0, 0, 1, 1, 0) (0, 0, 1, 2, 0) (2, 2, 2, 2, 2) (3, 2, 2, 2, 2) (3, 2, 2, 3, 2) (3, 2, 2, 4, 2)

The goal is to calculate the value of every counter after all operations.

Write a function:

  • def solution(N, A)

that, given an integer N and a non-empty array A consisting of M integers, returns a sequence of integers representing the values of the counters.

Result array should be returned as an array of integers.

For example, given:

A[0] = 3 A[1] = 4 A[2] = 4 A[3] = 6 A[4] = 1 A[5] = 4 A[6] = 4

the function should return [3, 2, 2, 4, 2], as explained above.

Write an efficient algorithm for the following assumptions:

  • N and M are integers within the range [1..100,000];
  • each element of array A is an integer within the range [1..N + 1].

 

대충 해석하면 N개만큼의 counters가(간편하게 배열이라고 생각하자) 있고 A[K]의 값을 X라고 하면

X가 1<= X <= N 이면 counters의 X번째는 + 1

X가 N+1 이면 counters중 가장 큰 counter로 전부 변환한다.

 

첫 번째 시도

23분 걸려서 만든 거..

그렇게 어렵게 생각하지 않은 코드다.

def solution(N, A):

    counters = [0 for _ in range(N)]

    for i in A:
        if i == N + 1:
            excounters = sorted(counters)
            for j in range(N):
                counters[j] = excounters[-1]
        else:
            counters[i-1] += 1

    return counters

아무래도 counters를 초기화하는 문제 때문에 O(N*M)이 나온 듯하다

 

 

두 번째 이후로 아주 많은 시도....

진짜로 한참 동안 고민했다.

합하면 2시간 넘게 걸린 문제, 대략 2시간 30분 정도 걸린 듯하다

어떻게 하면 for문을 하나로 돌릴까...

최댓값을 이용하면 되는건 알겠는데 거의 다 왔는데 끝에서 막힌 느낌이 들어서 계속 생각했다.

조금씩 조금씩 수정하면서 만들었던 코드다.

def solution(N, A):
    counters = []
    c = {}
    maxnum = 0
    for i in A:
        if i<N+1:
            if i in c:
                c[i] += 1
            else:
                c[i] = 1
        else:
            if c:
                if maxnum == 0:
                    maxnum = sorted(c.values())[-1]
                else:
                    maxnum += sorted(c.values())[-1]
            c = {}

    counters = [maxnum for _ in range(N)]

    if c:
        for i in c:
            counters[i-1] += c[i]
        

    return counters

 

풀이과정을 다시 복기해보자면

X가 N+1이 될 경우엔 counters의 최대값을 관리해주는 것이 관건이므로

c라는 dict를 만들어 일반 상황일 땐 c+=1을 해주고

만약 X = N+1이라면 dict 중 최댓값을 구하여 maxnum에 저장해둔다

만약 나중에 또 X = N+1이 나올 것을 대비하여 maxnum이 0이 아닌지를 체크한다.

그리고 처음부터 X = N+1이 나와버리는 불상사가 발생하게 된다면 빈 c dict에서 에러가 나게 되어버리므로

if c: 를 넣어 c가 있는지 체크를 했다.

 

진짜 거의 다 풀었는데 뭔가 하나를 틀려서 배열로 돌아갔다가, 약한 참조 하는 방법 찾다가

다시 돌고 돌아 dictionary로 풀었다.

만약 안 돌아가고 dict로 계속 팠으면 1시간이면 풀었을 문제...

막상 풀고 나니 이렇게 쉬웠던 문제를 왜 못 풀었는지 자괴감이 든다 :(