Hey 👋🏽
This is a solution in response to this problem solving problem from hackerrank:
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 and the maximum sum is 1 + 3 + 5 + 7 = 16. 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 4 of 5 elements.
Input Format
A single line of five space-separated integers.
Constraints
1<=arr[i]<=109
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.
My approach:
- Add all array elements using
reduce
. - Subtract from the sum the minimum value in the array. This get the maximum sum.
- Subtract from the sum the maximum value in the array. This get the minimum sum.
function miniMaxSum(arr) {
let sum = arr.reduce((a, b) => {
return a + b;
});
const min = sum - Math.max(...arr);
const max = sum - Math.min(...arr);
console.log(min + " " + max);
}
Thanks for reading 🥰.
Top comments (5)
Thanks for your solution. Here is another approach:
why did you use arr.sort() ? would you like to explain it for me please🙏🏻
This is really a good tutorial. it simplifies things and has a very good reasoning
Thank you everyone for the solution, I would like to share another approach:
function miniMaxSum(arr) {
arr.sort((a, b) => a - b);
const minSum = arr[0] + arr[1] + arr[2] + arr[3];
const maxSum = arr[1] + arr[2] + arr[3] + arr[4];
console.log(minSum, maxSum);
}
I think this not is a good approach, because if you doing the time complexity of this function is huge, practically you are traversing the array 3 times, in reduce, Math.max and Math.min function, that's mean 0(n) x 3. My approach is this:
miniMaxSum(arr) {
let vector = [-1, Number.MAX_SAFE_INTEGER];
let sum = 0;
}