function miniMaxSum(arr) {
// Write your code here
let max = Math.max(...arr);
let min = Math.min(...arr);
let minsum = 0;
let maxsum = 0;
for (let x in arr) {
if (arr[x] != max) {
minsum += arr[x];
};
if (arr[x] != min) {
maxsum += arr[x];
}
};
console.log(minsum, maxsum);
}
I got this from hackerrank, and apparently it fails certain test cases but I have to pay 5 "hackos" to learn why
my simple code
function miniMaxSum(arr) {
var max = 0;
var min = 0;
arr.sort();
for(var i = 0;i<arr.length;i++){
if(i>0 ){
max = max + arr[i];
}
if(i<4){
min = min + arr[i];
}
}
console.log(min + " " + max);
}
Are all the integers supposed to be unique? If not then this may not work if there are duplicates of max and min numbers?
For example [2,2,3,5,5]
So, I just got the problem to understand what it is supposed to do. What you need to do is to find the 4 biggest values in an array of integers and sum it, and also need to find the 4 smallest values and sum it. (hackerrank link: https://www.hackerrank.com/challenges/mini-max-sum/problem)
I'll let the code down below with comments so you can understand
function miniMaxSum(arr) {
//make a copy of the original array to calculate the max sum value
let arrMax = [...arr];
//make a copy of the original array to calculate the min sum value
let arrMin = [...arr];
let maxSum = 0;
let minSum = 0;
// We need to find the sum of the biggest/lowest 4 values
for (let i = 0; i < 4; i++) {
//find the index of the element with the biggest value
let maxElementIndex = arrMax.findIndex(value => value === Math.max(...arrMax));
//sum the value to the max sum result
maxSum += arrMax[maxElementIndex];
//remove the value from the array
arrMax.splice(maxElementIndex,1);
// here I am doing the same, but now to get the lowest value
let minElementIndex = arrMin.findIndex(value => value === Math.min(...arrMin));
minSum += arrMin[minElementIndex];
arrMin.splice(minElementIndex,1);
}
console.log(`${minSum} ${maxSum}`);
}
Now, some tips for you before you create a new question.
I hope I could help you. You can leave any comment if something is difficult to understand and I will try to help you. And happy coding! :)