Work/Algorithm

코딜리티 레슨4 Counting Elements 2 - MaxCounters

다랑 2020. 12. 3. 11:16
728x90

문제

 

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

Copyright 2009–2020 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited.

→ N으로 생성된 배열을 주어진 배열 A의 요소 값을 위치로 +1 한다. 말로 설명하기 어렵구먼

 

답변

 

1. 배열의 asis와 tobe 안에서 규칙을 발견한다.

2. 크기 N의 신규배열 arr의 값은 배열 A 요소가 위치가 되어 +1 된다.

3. 만약 A의 요소 값이 N+1인 경우 신규배열 arr의 모든 값은 당시 arr의 value 최대 값으로 변환된다.

(말로 설명하기 어렵구만.)

4. 구지 중첩for문을 사용할 이유가 없다.

5. N+1인 경우의 규칙을 따로 찾는다 → 최대값을 잡아두고 나중에 더하는 방식으로 정했다.

 

class Solution {
    public int[] solution(int N, int[] A) {
        // write your code in Java SE 8
        int[] arr = new int[N];
        int tmpMax=0, finMax =0;
        
        for(int a : A) {
            if(a == N+1) {
                finMax = tmpMax;
            } else {
                if(arr[a-1] < finMax) arr[a-1] = finMax + 1;
                else arr[a-1]++;
                if(tmpMax < arr[a-1]) tmpMax = arr[a-1];
            }
        }
        
        for(int i=0;i<N;i++) {
            if(arr[i] < finMax)
                arr[i] = finMax;
        }
        
        return arr;
    }
}

 

결과

 

https://app.codility.com/demo/results/training2VS72T-PGH/

처음에는 77점 받았다.

꼭 하나씩 놓친다. 으휴, 더 연습해야지

시간복잡도(Detected time complexity): O(N + M)

728x90