Objective:
Calculate the minimum and maximum sums of four out of five integers.
Mini-Max Sum Problem Statement:
It says you are given an array of five positive integers. Your task is to calculate the minimum and maximum sum (mini-max sum) obtained by summing exactly four of the five integers.
Input Format:
- A single line of five space-separated integers.
Output Format:
- Two space-separated integers where:
- The first integer is the minimum sum.
- The second integer is the maximum sum.
Example 1:
- Input:
- 1 2 3 4 5
- Output:
- 10 14
- Explanation: The minimum sum is obtained by summing the smallest four numbers (1 + 2 + 3 + 4 = 10). The maximum sum is obtained by summing the largest four numbers (2 + 3 + 4 + 5 = 14).
Example 2:
- Input:
- 7 69 2 221 8974
- Output:
- 299 9271
- Explanation: The minimum sum is obtained by summing the smallest four numbers (7 + 69 + 2 + 221 = 299). The maximum sum is obtained by summing the largest four numbers (69 + 221 + 8974 + 7 = 9271).
Example 3:
- Input:
- 5 5 5 5 5
- Output:
- 20 20
- Explanation: Since all numbers are the same, both the mini-max sum are the same (5 + 5 + 5 + 5 = 20).
Steps to Solve:
- Sort the Array: Sort the list of integers.
- Calculate Minimum Sum: Sum the first four (smallest) numbers.
- Calculate Maximum Sum: Sum the last four (largest) numbers.
- Print the Results: Output the minimum sum and the maximum sum as space-separated integers.
Hints: Beware of integer overflow! Use 64-bit Integer.
Mini-Max Sum Problem Snippet
Solution:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;
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
Collections.sort(arr);
long min = 0, max = 0;
int length = arr.size()-1;
for(int i=0; i<length; i++){
min += arr.get(i);
max += arr.get(length-i);
}
System.out.print(min+" "+max);
}
}
public class Solution {
public static void main(String[] args) throws IOException {
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
List<Integer> arr = Stream.of(bufferedReader.readLine().replaceAll("\\s+$", "").split(" "))
.map(Integer::parseInt)
.collect(toList());
Result.miniMaxSum(arr);
bufferedReader.close();
}
}
The Problem Solution