본문 바로가기

알고리즘/Hackerrank

[Hackerrank] Picking Numbers

Given an array of integers, find the longest subarray where the absolute difference between any two elements is less than or equal to 1.

 

Example

 

a = [1,1,2,2,4,4,5,5,5]

 

There are two subarrays meeting the criterion: [1,1,2,2] and [4,4,5,5,5]. The maximum length subarray has 5 elements.

 

Function Description

 

Complete the pickingNumbers function in the editor below.

pickingNumbers has the following parameter(s):

- int a[n]: an array of integers

 

Returns

- int: the length of the longest subarray that meets the criterion

 

Input Format

 

The first line contains a single integer n, the size of the array a.

The second line contains n space-separated integers, each an a[i].

 

Constraints

 

- 2 <= n <= 100

- 0 < a[i] < 100

- The answer will be >= 2.

 

Sample Input 0

6
4 6 5 3 3 1

 

Saple Output 0

3

 

Explanation 0

 

We choose the following multiset of integers from the array:{4,3,3}. Each pair in the multiset has an absolute difference <= 1 (i,e.,|4-3| = 1 and |3-3| = 0), so we print the number of chosen integers,3,as our answer.

 

Sample Input 1

6
1 2 2 3 1 2

 

Sample Output 1

5

 

Explanation 1

 

We choose the following multiset of integers from the array:{1,2,2,1,2}. Each pair in the multiset has an absolute difference <= 1(i.e.,|1-2| = 1, |1-1| = 0, and |2-2| = 0), so we print the number of chosen integers,5,as our answer.

 

더보기

criterion : 기준

below : 아래에

 

- 배열이 주어진다.

- 배열에서 두수의 차이가 1보다 작거나 같은 하위배열중 가장 긴 하위배열을 찾는다.

- 그 배열의 길이를 return 한다.

 

    public static int pickingNumbers(List<Integer> a) {
    // Write your code here
        int[] arr = new int[100];
        int max = 0;
        
        for(int i=0; i<a.size(); i++) {
            arr[a.get(i)]++;
        }
        
        for(int i=0; i<arr.length-1; i++) {
            if(arr[i] + arr[i+1] > max) {
                max = arr[i] + arr[i+1];
            }
        }
        
        return max;
    }

 

풀이

- 최대 100 길이의 배열이 a로 들어오니, 100길이의 arr를 선언한다. 

- 선언한 arr에 a배열에 들어있는 값에 맞춰 증가시켜준다.

- 인접한 두 수 중에 큰수를 max로 담고 return

 

'알고리즘 > Hackerrank' 카테고리의 다른 글

[Hackerrank] Operators  (0) 2021.09.25
[Hackerrank] Data Types  (0) 2021.09.25
[Hackerrank] Forming a Magic Square  (0) 2021.09.23
[Hackerrank] Java Loops 1  (0) 2021.09.23
[Hackerrank] Java Output Formatting  (0) 2021.09.23