Link to HackerRank Challenge
My idea is to loop through the array and sum all elements in the array except for one element each time, then find the smallest sum and the largest sum.
I know that .splice() can remove any element from an array. But currently, with my code, it's only removing one element from the array once. I.e. this is only giving me one chunk:
function miniMaxSum(arr) {
let smallestSum = 0;
let largestSum = 0;
for (let i = 0; i < arr.length; i++) {
let chunk = arr.splice(1);
console.log(chunk);
if (chunk > largestSum) largestSum = chunk;
if (chunk < smallestSum) smallestSum = chunk;
}
return (smallestSum, largestSum);
}
I need to remove one element from the array every time while looping, then get the max and min sums from that array.
So for given array of [1, 2, 3, 4, 5]
I should get the following possible "chunks":
[2, 3, 4, 5], [1, 3, 4, 5], [1, 2, 4, 5], [1, 2, 3, 5], [1, 2, 3, 4].
The chunk with the highest sum is [2, 3, 4, 5]
And the chunk with the smallest sum is [1, 2, 3, 4].
How can I adjust my code to get all of the possible 4-digit arrays within the given array so that I can compare their sums, still using a for-loop? Or if not with a for-loop, what else would you suggest?
EDIT: Now using Math.min() and Math.max() to get the smallest and largest elements in the array. Then using .filter() to remove those elements in order to create new arrays. Then getting the sums of those arrays.
function miniMaxSum(arr) {
let smallest = Math.min(...arr);
let largest = Math.max(...arr);
let smallestArray = arr.filter(element => element !== largest);
let largestArray = arr.filter(element => element !== smallest);
let sumOfSmallestArray = 0;
let sumOfLargestArray = 0;
for (let i = 0; i < smallestArray.length; i++) {
sumOfSmallestArray += smallestArray[i];
}
for (let i = 0; i < largestArray.length; i++) {
sumOfLargestArray += largestArray[i];
}
return ([sumOfSmallestArray, sumOfLargestArray]).toString();
}
But even though it works in my console, it doesn't work in HackerRank.
The key is to sort that array first, then the minimum will be the first element and the maximum will be the last, hence if you want to get the minimum set, it will be the array without the highest value (last element) and if you want to get the maximum set it will be the array without the lowest value (first element).
let data = [1, 3, 2, 4, 5];
// sort first
data = data.sort((a, b) => a - b);
// to get the sets only
let maxSet = data.slice(1);
let minSet = data.slice(0, -1);
console.log(minSet, maxSet);
// to get just the max/min value
const sum = data.reduce((a, total) => a + total, 0);
console.log(sum - data[data.length - 1], sum - data[0]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With