My approach to solving HackerRank’s Mini-Max Sum code challenge.
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 12
Input format
A single line of five space-separated integers.
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.
Sample input
1 2 3 4 5
Sample output
10 14
Solution
Firstly, we will calculate a total sum of array elements using the Array.reduce() function and store the result as arrSum.
Then a temporary empty array (tmp) is created to be used later.
After that, we create a for loop where we will go through the given array. During each loop, we subtract the current loop's value (arr[i]) from the total sum of array elements arrSum and push the result to the temporary array (tmp) using the Array.push() method.
Finally, we print results (console.log) of the minimum (Math.min()) and maximum (Math.max()) values from a temporary array (tmp).
Solution complexity: O(n).
function miniMaxSum(arr) {
const arrSum = arr.reduce((a, b) => a + b);
let tmp = [];
for (let i = 0; i < arr.length; i++) {
tmp.push(arrSum - arr[i]);
}
console.log(Math.min(...tmp), Math.max(...tmp));
}