2023. 1. 27. 13:28ㆍJava/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
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 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 1, 2, 3, 4 and 5. Calculate the following sums using four of the five integers:
- Sum everything except 1, the sum is
2 + 3 + 4 + 5 = 14
. - Sum everything except 2, the sum is
1 + 3 + 4 + 5 = 13
. - Sum everything except 3, the sum is
1 + 2 + 4 + 5 = 12
. - Sum everything except 4, the sum is
1 + 2 + 3 + 5 = 11
. - Sum everything except 5, the sum is
1 + 2 + 3 + 4 = 10
.
5개의 양수가 주어집니다
주어지는 수 중 4개의 합의 최소값과 최대값을 출력하는 코드를 짜면 됩니다.
각 요소의 최소값은 1 최대값은 로, int 자료형의 최대값이 약 정도이기 때문에 표현 가능합니다.
합산은 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); }
'Java > coding test' 카테고리의 다른 글
[HackerRank - Java] Day 2 - 1. Lonely Integer (0) | 2023.01.27 |
---|---|
[HackerRank - Java] Day 1 - 3. Time Conversion (0) | 2023.01.27 |
[HackerRank - Java] Day 1 - 1. Plus Minus (0) | 2023.01.27 |
[Codility - Java] 10. Prime and composite numbers - 1. CountFactors (0) | 2023.01.11 |
[Codility - Java] 8. Leader - 2. EquiLeader (0) | 2023.01.10 |