[HackerRank - Java] Day 1 - 2. Mini-Max Sum

2023. 1. 27. 13:28Java/coding test

반응형

Mini-Max Sum

Given five positive integers, find the minimum and maximum values that can be calculated by summing exactly four of the five integers. Then print the respective minimum and maximum values as a single line of two space-separated long integers.

Example

arr=[1,3,5,7,9]arr = [1, 3, 5, 7, 9]

The minimum sum is 1 + 3 + 5 + 7 = 16 and the maximum sum is 3 + 5 + 7 + 9 = 24. The function prints

16 24

Function Description

Complete the miniMaxSum function in the editor below.

miniMaxSum has the following parameter(s):

  • arr: an array of integers

Print

Print two space-separated integers on one line: the minimum sum and the maximum sum of of elements.

Input Format

A single line of five space-separated integers.

Constraints

1<=arr[i]<=1091 <= arr[i] <= 10^9

Output Format

Print two space-separated long integers denoting the respective minimum and maximum values that can be calculated by summing exactly four of the five integers. (The output can be greater than a 32 bit integer.)

Sample Input

1 2 3 4 5

Sample Output

10 14

Explanation

The numbers are 1, 2, 3, 4 and 5. Calculate the following sums using four of the five integers:

  1. Sum everything except 1, the sum is 2 + 3 + 4 + 5 = 14.
  2. Sum everything except 2, the sum is 1 + 3 + 4 + 5 = 13.
  3. Sum everything except 3, the sum is 1 + 2 + 4 + 5 = 12.
  4. Sum everything except 4, the sum is 1 + 2 + 3 + 5 = 11.
  5. Sum everything except 5, the sum is 1 + 2 + 3 + 4 = 10.

5개의 양수가 주어집니다
주어지는 수 중 4개의 합의 최소값과 최대값을 출력하는 코드를 짜면 됩니다.

각 요소의 최소값은 1 최대값은 10910^9 로, int 자료형의 최대값이 약 21092 * 10^9 정도이기 때문에 표현 가능합니다.


합산은 int 자료형의 표현범위를 넘어갈 수 있기 때문에 long 타입을 사용해야합니다.

static void miniMaxSum(List<Integer> arr) {
    int max = 0, min = Integer.MAX_VALUE;
    long total = 0;
    for (int i : arr) {
        if(max < i) max = i;
        if(min > i) min = i;
        total += i;
    }
    System.out.printf("%d %d%n", total - max, total - min);
}
728x90
반응형