Reputation: 74
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"
Upvotes: 1
Views: 2514
Reputation: 71
Try this solution if you are used to Java.
import java.util.ArrayList;
public class ArrayExcept {
public static void main(String[] args) {
ArrayList<Integer> ai = new ArrayList<>(5);
ai.add(7);
ai.add(69);
ai.add(2);
ai.add(221);
ai.add(8974);
int total =0;
int max = ai.get(0);
int min = ai.get(0);
for(int n : ai){
total+=n;
if (n<min) {
min = n;
}
if (n>max) {
max = n;
}
}
System.out.println((total - min) + " " + (total - max));
}
}
Upvotes: 0
Reputation: 11
mx = max(arr)
mi = min(arr)
i = 0
for i in range(0,len(arr)):
a = sum(arr) - mx
b = sum(arr) - mi
print(a,b)
Upvotes: 0
Reputation: 350477
Some issues:
filter
call will return an empty array, on which reduce
is called. As reduce
is called without the "initial value" argument, a run-time error will occur.Not a problem, but:
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}`);
}
Upvotes: 1
Reputation: 28196
@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}`
}
Upvotes: 1