I am working on Hackerrank challenge Mini-Max Sum:
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 is3 5 7 9 = 24
.The function prints
16 24
I submitted the below code, but it doesn't pass one sample test case. Is there anything wrong in my code?
function miniMaxSum(arr) {
let set = [...new Set(arr)];
const MIN = set.filter((num) => num !== Math.max(...set)).reduce((sum, num) => sum num);
const MAX = set.filter((num) => num !== Math.min(...set)).reduce((sum, num) => sum num);
console.log(MIN ' ' MAX);
}
The error is a "Runtime Error"
CodePudding user response:
Some issues:
- A problem will occur when all 5 input values are equal. In that case the
filter
call will return an empty array, on whichreduce
is called. Asreduce
is called without the "initial value" argument, a run-time error will occur. - There is no indication in the challenge that duplicate values should only be accounted for once in the sum. So if the input does contain duplicate values, this will not always produce correct results.
Not a problem, but:
- Calculating the min/max in each iteration of the
filter
callback is not efficient -- it will be the same result every time, so better calculate this only once.
Here is a working solution that takes the above points into consideration:
function miniMaxSum(arr) {
const sum = arr.reduce((a, b) => a b);
const min = sum - Math.max(...arr);
const max = sum - Math.min(...arr);
console.log(`${min} ${max}`);
}
CodePudding user response:
@Trincot already explained the error in all details. Nothing to be added there.
Here is yet another way of doing it by avoiding redundant calculations:
function mms(arr) {
const [a,...ar]=arr;
let [min,max,sum]=[a,a,a];
ar.forEach(c=>{
if(c<min) min=c
else if (c>max) max=c
sum =c
});
return `${sum-max} ${sum-min}`
}