Coding Test/HackerRank
[HackerRank] Mini-Max Sum c++
owls
2022. 7. 16. 23:06
728x90
- 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
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
- constraints
1 <= arr[i] <= 10^9
- 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+4+5 = 11.
- Sum everything except 5, the sum is 1+2+3+4 =10.
Hints: Beware of integer overflow! Use 64-bit Integer.
- solution
처음에는 nMin, nMax를 int형으로 선언했는데 overflow가 났습니다.
Hints에 적혀있는걸 나중에 봤네요.
범위 체크!!
다시 long long으로 바꾸고 실행시키니 통과!
void miniMaxSum(vector<int> arr) {
sort(arr.begin(), arr.end());
long long nMin = 0, nMax = 0;
long long n = long(arr.size());
for (int i = 0; i < n - 1; i++) {
nMin += arr[i];
nMax += arr[n - 1- i];
}
cout << nMin << " "<< nMax;
}
728x90