개발 여정/코딩테스트 준비

HackerRank 1달 과정 1주차 2번 - Mini-Max Sum

calm-lee 2021. 12. 5. 23:37

 

https://www.hackerrank.com/challenges/one-month-preparation-kit-mini-max-sum/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=preparation-kits&playlist_slugs%5B%5D=one-month-preparation-kit&playlist_slugs%5B%5D=one-month-week-one 

 

 

5가지 int 숫자의 배열이 주어지면

이 중 4가지 숫자의 합을 구해서 그 중 최대값, 최소값을 구하는 문제이다.

class Result {

    public static void miniMaxSum(List<Integer> arr) {

    
    long min_sum = 0; // 가장 작은 합
    long max_sum = 0; // 가장 큰 합
    long total_sum = 0; // 모든 5가지 숫자를 더 했을 때 합
    
    // List -> Array 변환
    Integer[] array = arr.toArray(new Integer[5]);

	// total_sum 구하기
    for(int i = 0; i < 5; i++){
        total_sum += array[i];
    }
    
    // 4가지 숫자만 더한 값의 배열 만들기
    long[] sum_arr = new long[5];
    
    // sum_arr에 4가지 숫자만 더한 값 넣기
    for(int i = 0; i < 5; i++){
       sum_arr[i] = total_sum - array[i];
    }  
    
   // sum_arr 오름차순으로 정렬하기
    Arrays.sort(sum_arr);
    
    min_sum = sum_arr[0]; // 가장 작은 합
    max_sum = sum_arr[4]; // 가장 큰 합
    
    System.out.println(min_sum + " " + max_sum);

    }

}

*arr[i]의 값 제한이 1~10의 9승이기 때문에 int형이 아닌 long형으로 변수들을 선언했다.

 

처음부터 array로 주면 안되는지.. 왜 자꾸 List로 주는지...

배열 정렬 함수는 은근히 코테에 자주 쓰이는 것 같다.