📜  mini-max sum hackerrank - C 编程语言(1)

📅  最后修改于: 2023-12-03 15:32:54.638000             🧑  作者: Mango

Mini-Max Sum

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 Format

Input should be an array of 5 integers.

Output Format

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.

Sample Input
1 2 3 4 5
Sample Output
10 14
Explanation

The possible combinations of 4 numbers and their sums are:

  • 1 + 2 + 3 + 4 = 10
  • 1 + 2 + 3 + 5 = 11
  • 1 + 2 + 4 + 5 = 12
  • 1 + 3 + 4 + 5 = 13
  • 2 + 3 + 4 + 5 = 14

Therefore, the minimum possible sum is 10 and the maximum possible sum is 14.

C Solution

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:

  • We first declare an array arr of size 5, and two variables min_sum and max_sum to store the results.
  • We then take input of 5 integers using a for loop and scanf function.
  • We use two nested for loops to calculate the minimum and maximum sum.
  • Inside the nested for loops, we calculate the sum of 4 numbers by excluding the i-th element and store it in the variable sum.
  • If the calculated sum is the minimum (in case of the first iteration) or smaller than the current value of min_sum, we update min_sum.
  • Similarly, if the calculated sum is the maximum (in case of the first iteration) or greater than the current value of max_sum, we update max_sum.
  • Finally, we print the minimum and maximum sum using 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.