MaxCounters 문제 링크
https://app.codility.com/c/run/trainingP5XD3A-G9T/
Summary
효율적인 개수 세기
You are given N counters, initially set to 0, and you have two possible operations on them:
A non-empty array A of M integers is given. This array represents consecutive operations:
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].
- 혼자서 문제를 해결
- 힌트를 보고 해결
- 답을 보고 해결
def solution(N, A):
lis = [0] * N
max_val = 0
for n in A:
if n <= N:
lis[n-1] +=1
if max_val < lis[n-1]:
max_val = lis[n-1]
else:
lis = [max_val]*N
return lis
def solution(N, A):
counters = N * [0]
next_max_counter = max_counter = 0
for oper in A:
if oper <= N:
current_counter = counters[oper-1] = max(counters[oper-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]
Codility는 효율성 통과가 정말 힘들다.....
마지막 테스트 케이스를 통과하기 위해 어떻게 해야할지 정말 고민이 많았다. max_val로 다시 리스트를 만드는 부분을 수정해야한다는 생각이 들었지만 결국 해결하지 못했다.
다른 사람 풀이를 보고 마지막에 최대값을 저장해두고 한번에 처리하면 되겠구나 하는 인사이트를 얻을 수 있었다.
연산할 때 필요한 값을 한번에 처리할 수 있도록 코드 구성을 해보자.
값을 비교할 때, 깔끔한 코드 표현을 위해 연산자보다 내장함수(max, min, ...)를 사용해보자.