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:
class Solution { public int[] solution(int N, int[] 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].
나의 문제 해결:
function solution(N, A) {
let result = Array(N).fill(0); // N개의 배열을 0으로 초기화
let lastMax = 0; // 마지막 최대값을 가지는 변수
let max = 0; //A의 최대값을 저장하기 위한 변수
for(let i=0; i< A.length; i++){
// N+1의 값과 A의 값이 같은경우 (문제의 A[3]은 6이고, N은 5 일 경우)
if (A[i] === N + 1) {
lastMax = max;
} else {
const index = A[i] - 1 //A의 index값을 구하고
if(result[index] < lastMax) result[index] = lastMax;
result[index]++;
if (result[index] > max) max = result[index]
}
}
for(let x=0; x< N; x++){
if(result[x] < lastMax){
result[x] = lastMax //lastMax 작은경우 배열의 모든값에 lastMax로 값 변경
}
}
return result;
}
처음시도 코드: Array의 fill 함수가 for문처럼 오래걸리는지 몰랐음.
function solution(N, A) {
let result = Array(N).fill(0);
let max = 0;
for(let i=0; i< A.length; i++){
if (A[i] === N + 1) {
result = Array(N).fill(max) // 이부분 떄문에 77퍼센트 성공
} else {
const index = A[i] - 1
result[index]++
if (result[index] > max) max = result[index]
}
}
return result;
}
'IT > Algorithm' 카테고리의 다른 글
코딜리티(Codility) Lesson4 CountDiv 문제풀기 (0) | 2021.05.27 |
---|---|
코딜리티(Codility) Lesson4 PermCheck 문제풀기 (0) | 2021.05.12 |
코딜리티(Codility) Lesson3 TapeEquilibrium 문제풀기 (0) | 2021.03.04 |
코딜리티(Codility) Lesson3 PermMissingElem 문제풀기 (0) | 2021.03.02 |
코딜리티(Codility) Lesson3 FrogJmp 문제풀기 (0) | 2021.02.28 |