1. JavaScript
정해
function solution(N, A) {
let counters = new Array(N).fill(0);
let max = 0;
let lastMax = 0;
for(let k of A){
if(k <= N){
if(counters[k - 1] < lastMax){
counters[k - 1] = lastMax;
}
counters[k - 1]++;
if(max < counters[k -1]){
max = counters[k - 1];
}
}else{
lastMax = max;
}
}
for(let i = 0; i < N; i++){
if(counters[i] < lastMax){
counters[i] = lastMax;
}
}
return counters
}
- Math.max로 매번 최댓값을 구하기 어렵기 때문에 다음과 같은 방식을 사용하는 것 같다.
50%
function solution(N, A) {
let count = Array(N).fill(0);
for (i = 0; i < A.length; i++) {
if (1 <= A[i] && A[i] < N) {
count[A[i] - 1] += 1;
} else {
count.fill(Math.max(...count));
}
}
return count;
}
console.log(solution(5, [3, 4, 4, 6, 1, 4, 4]))
2. Python
정해
def solution(N,A):
savemaximum = 0
maximum = 0
counter = [0]*N
for i in range(len(A)):
if A[i]<=N:
if counter[A[i]-1]<savemaximum:
counter[A[i]-1]=savemaximum
counter[A[i]-1]+=1
maximum = max(counter[A[i]-1],maximum)
else:
savemaximum = maximum
for i in range(N):
if counter[i]<savemaximum:
counter[i]=savemaximum
return counter
출처: https://imksh.com/68 [강승현입니다]
60%
def solution(N, A):
result = [0] * N
for i in A:
if 1 <= i <= N:
result[i-1] += 1
else:
result = [max(result)] * N
return result