Stay hungry, Stay foolish

[codility] MaxCounters 본문

알고리즘, 자료구조

[codility] MaxCounters

Jake2 2022. 10. 18. 22:02

최근에 코테를 봐야 할 일들이 많이 생겨서 부랴부랴 코테 공부를 하고 있습니다.

반복적으로 풀다보면 깨닫은 것 중 하나가 for loop 중 최댓값 or 최솟값 등을 체크 해야하는 문제들이 더러 있는데,

loop 안에서 arr 전체에 max or min 메서드를 사용하면 O(n**2) 이 되어 버립니다.

이런경우는 이 전 max or min_cnt 등의 변수에 저장시킨 값과 현재 loop를 돌며 나온 cnt의 값을 비교시키는 방법을 사용하면 효율을 개선시킬 수 있습니다! 

문제랑 코드 보겠습니다.

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].

 

# O(n**2)

def solution(N, A):
    counters = [0 for _ in range(N)]
    

    for i in A:
        if i <= N:
            counters[i-1] += 1
        else:
            max_counter = max(counters)
            counters = [max_counter for _ in counters]

    return counters

-> 맨 처음 의식의 흐름대로 써내려간 풀이 

def solution(N, A):

    counters = N * [0]
    next_max_counter =  max_counter = 0

    for i in A:
        if i <= N:
            current_counter = counters[i-1] = max(counters[i-1] +1, max_counter+1)
            next_max_counter = max(current_counter, next_max_counter)
        else:
            max_counter = next_max_counter

    return [c if c > max_counter else max_counter for c in counters]

-> 다른 사람의 풀이  ..... 👏👏👏👏 

'알고리즘, 자료구조' 카테고리의 다른 글

(lv.1) 숫자 문자열과 영단어  (0) 2022.04.24
Comments