📅  最后修改于: 2023-12-03 15:32:54.638000             🧑  作者: Mango
Mini-Max Sum is a problem on HackerRank where you have to find the minimum and maximum possible sums of 4 out of 5 integers in an array.
Input should be an array of 5 integers.
Output should be two integers separated by space where the first integer is the minimum possible sum and the second integer is the maximum possible sum.
1 2 3 4 5
10 14
The possible combinations of 4 numbers and their sums are:
Therefore, the minimum possible sum is 10 and the maximum possible sum is 14.
Here is a C solution to the problem:
#include <stdio.h>
int main() {
int arr[5], min_sum = 0, max_sum = 0;
for (int i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
// Find the minimum sum
for (int i = 0; i < 5; i++) {
int sum = 0;
for (int j = 0; j < 5; j++) {
if (i != j) {
sum += arr[j];
}
}
if (i == 0 || sum < min_sum) {
min_sum = sum;
}
}
// Find the maximum sum
for (int i = 0; i < 5; i++) {
int sum = 0;
for (int j = 0; j < 5; j++) {
if (i != j) {
sum += arr[j];
}
}
if (i == 0 || sum > max_sum) {
max_sum = sum;
}
}
printf("%d %d", min_sum, max_sum);
return 0;
}
Explanation:
arr
of size 5, and two variables min_sum
and max_sum
to store the results.scanf
function.sum
.sum
is the minimum (in case of the first iteration) or smaller than the current value of min_sum
, we update min_sum
.sum
is the maximum (in case of the first iteration) or greater than the current value of max_sum
, we update max_sum
.printf
function.Note: This solution has a time complexity of O(n^2) because of the nested for loops. However, for small input sizes such as 5, this solution is efficient enough. For larger input sizes, a more optimized algorithm can be used.