Problem
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
The minimum sum is and the maximum sum is . 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 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
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 , , , , and . Calculate the following sums using four of the five integers:
- Sum everything except , the sum is .
- Sum everything except , the sum is .
- Sum everything except , the sum is .
- Sum everything except , the sum is .
- Sum everything except , the sum is .
Hints: Beware of integer overflow! Use 64-bit Integer.
주어진 다섯 개의 양의 정수에 대해, 그 중 정확히 네 개의 정수를 합산하여 계산할 수 있는 최소값과 최대값을 찾습니다. 그리고 각각의 최소값과 최대값을 공백으로 구분하여 한 줄에 출력합니다.
예시
- 최소 합은 10이고 최대 합은 14입니다. 출력은 10 14입니다.
Solution
내가 작성한 코드는 다음과 같다.
이 문제는 쉬운 것 같으면서도 문제 마지막을 보면 중요한 문구가 숨어있었다!
Hints: Beware of integer overflow! Use 64-bit Integer.
이것을 강조하는 이유는 내가 이것을 제대로 확인하지 않아서 처음에 제출 시 어떤 것은 맞고 어떤 것은 틀렸었기 때문이다.
class Result {
/*
* Complete the 'miniMaxSum' function below.
*
* The function accepts INTEGER_ARRAY arr as parameter.
*/
public static void miniMaxSum(List<Integer> arr) {
// Write your code here
int min = arr.get(0); // 초기 최소값을 첫 번째 요소로 설정
int max = arr.get(0); // 초기 최대값을 첫 번째 요소로 설정
long sum = 0; // 합계를 저장할 변수
// 배열의 모든 요소를 순회
for (int i = 0; i < arr.size(); i++) {
sum += arr.get(i); // 합계에 현재 요소를 추가
// 최소값 찾기
if (min > arr.get(i)) {
min = arr.get(i);
}
// 최대값 찾기
if (max < arr.get(i)) {
max = arr.get(i);
}
}
// 최대값을 제외한 합계와 최소값을 제외한 합계를 출력
System.out.printf("%d %d", sum - max, sum - min);
}
}
합계를 저장하는 변수가 int가 아니라 long인 이유?
1. 정수 범위 차이
- int 데이터 타입은 32비트 정수로, 표현할 수 있는 값의 범위가 -2,147,483,648에서 2,147,483,647입니다.
- long 데이터 타입은 64비트 정수로, 표현할 수 있는 값의 범위가 -9,223,372,036,854,775,808에서 9,223,372,036,854,775,807입니다.
2. 합계의 크기
- 문제에서 다섯 개의 양의 정수를 합산하기 때문에, 최대값의 경우 각 정수가 최대 10억(1,000,000,000)이라고 가정하면:
- 최악의 경우: 5×1,000,000,000=5,000,000,0005 \times 1,000,000,000 = 5,000,000,000
- 이 값은 int의 최대 범위를 초과하므로, long을 사용하여 오버플로우를 방지해야 합니다.
'코딩 테스트' 카테고리의 다른 글
[HackerRank] Diagonal Difference (0) | 2024.09.24 |
---|---|
[HackerRank] Lonely Integer (2) | 2024.09.23 |
[HackerRank] Find the Median (5) | 2024.09.23 |
[HackerRank] Plus Minus (0) | 2024.09.23 |
[HackerRank] Time Conversion (0) | 2024.09.23 |