'Mini-Max Sum In JavaScript - How to Get the Minimum Sum And Maximum Sum of 4 Elements in a 5-Element Array
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.
Solution 1:[1]
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();
// 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]);
Solution 2:[2]
The HackerRank challenge just asks for the sums of the, so you can make one pass through the array to calculate 3 facts:
- Maximum element (
a
) - Minimum element (
b
) - Total sum of all elements (
c
)
The sum of the smallest chunk will be c - a
and the sum of the largest will be c - b
.
Here's a one-liner solution using reduce
:
var arr = [1, 2, 3, 4, 5];
var [a, b, c] = arr.reduce(([a, b, c], x) => [a > x ? a : x, b < x ? b : x, c + x], [NaN, NaN, 0]);
console.log(c - a, c - b);
Note: the NaN
's are just here to force the initial conditions (a > x
/b < x
to be false)
Solution 3:[3]
You could get the min and max values of the array and filter the array by taking not min or max value once.
var data = [1, 2, 3, 4, 5],
min = Math.min(...data),
max = Math.max(...data),
dataMin = data.filter(v => v !== min || !(min = -Infinity)),
dataMax = data.filter(v => v !== max || !(max = Infinity));
console.log(...dataMin);
console.log(...dataMax);
A more classical approach
function minMax(array) {
var min = array[0],
max = array[0],
sum = array[0],
i, v;
for (i = 1; i < array.length; i++) {
v = array[i];
sum += v;
if (v > max) max = v;
if (v < min) min = v;
}
console.log(sum - min, sum - max);
}
minMax([1, 2, 3, 4, 5]);
Solution 4:[4]
You can sort
the array and for min
take first four and add them and for max
take last four and add them
let arr = [1, 2, 3, 4, 5]
let minAndMax = (arr) => {
arr = arr.sort((a,b) => a - b)
let op = {}
op.minArr = arr.slice(0,4)
op.min = op.minArr.reduce((a,b) => a+b, 0)
op.maxArr = arr.slice(arr.length-4,)
op.max = op.maxArr.reduce((a,b) => a + b ,0)
return op
}
console.log(minAndMax(arr))
Solution 5:[5]
This solution traverses the slice indexes, calculates the sum and when a maximum is found, it is put into result. Finally result is parsed:
var arr = [4, 8, 2, 6, 12];
var ln = arr.length;
var maxSum = undefined;
var result = "";
for (var splIndex = 0; splIndex < ln; splIndex++) {
var item = arr.splice(splIndex, 1);
var sum = 0;
for (var it of arr) sum += it;
if ((maxSum === undefined) || (maxSum < sum)) {
maxSum = sum;
result = JSON.stringify(arr);
}
arr.splice(splIndex, 0, item[0]);
}
console.log(JSON.parse(result));
EDIT
A simpler solution, of course is to find the minimum and calculate the sum without it.
Solution 6:[6]
The following function works:
function miniMaxSum(arr) {
var _arr = arr.sort((a, b) = > a - b)
var minVals = _arr.slice(0, 4)
var maxVals = _arr.slice(1)
const arrSum = __arr = > __arr.reduce((a, b) = > a + b, 0)
var minSum = arrSum(minVals)
var maxSum = arrSum(maxVals)
console.log(minSum, maxSum)
}
Solution 7:[7]
let arr = [15 ,12, 33, 25, 4];
//sort array
const arrSort = arr.sort((a,b)=> a-b );
console.log(arrSort);
//get values and sum
var max = arrSort.filter(value => value < Math.max(...arrSort)).reduce((ac,at)=>{
ac += at;
return ac;
},0);
var min = arrSort.filter(value => value > Math.min(...arrSort)).reduce((ac,at)=>{
ac += at;
return ac;
},0);
console.log(max);
console.log(min);
Solution 8:[8]
This worked for me.
let minValue, maxValue
const ascendingArray = arr.sort((a,b) => a - b)
const smallestNumber = ascendingArray[0]
const biggestNumber = ascendingArray[ascendingArray.length -1]
if(smallestNumber !== biggestNumber){
const biggestArray = arr.filter((number) => {
return number !== smallestNumber
})
const smallestArray = arr.filter((number) => {
return number !== biggestNumber
})
minValue = smallestArray.reduce((a,b) => a + b, 0)
maxValue = biggestArray.reduce((a,b) => a + b, 0)
console.log(minValue, maxValue);
}
else{
const arraySliced = arr.slice(0, 4)
const value = arraySliced.reduce((a,b) => a + b, 0)
console.log(value, value);
}
Solution 9:[9]
function miniMaxSum(arr) {
var soma = 0
let t = 0
for (var i = 0; i < arr.length; i++) {
soma += arr[i]
max = soma - arr[i]
}
let min = soma - arr[0]
return max + ' ' + min
}
console.log(miniMaxSum([7, 69, 2, 221, 8974]))
Solution 10:[10]
Here is a cleaner approach to solving this problem.
function miniMaxSum(arr) {
let min, max, sum, arrMin, arrMax; // declare variables
min = Math.min(...arr) // gets the smallest value from the arr
max = Math.max(...arr) // gets the largest number from the arr
sum = arr.reduce((a,b) => a+b, 0); // reduce used to add all values in arr
arrMin = sum - max; // excludes the largest value
arrMax = sum - min; // excludes the smallest value
console.log(arrMin+' '+arrMax) // output
}
Solution 11:[11]
easy solution
const miniMax = arr => {
let min = arr[0];
let max = arr[0];
for(let i = 0; i < arr.length; i++) {
if(arr[i] <= min) {
min = arr[i];
}
if (arr[i] >= max) {
max = arr[i];
}
}
let sum = arr.reduce((acc,curr) => acc + curr);
console.log(sum - max, sum - min);
}
miniMax([5,5,5,5,5]);
// result : 20 20
miniMax([1,2,3,4,5]);
// result : 10 14
Solution 12:[12]
I get Answer in very Simple way
function miniMaxSum(arr) {
let minval=arr[0];
let maxval=0;
let totalSum=0;
for(let i=0;i<arr.length;i++){
if (arr[i]>maxval){
maxval=arr[i];
}
if (arr[i]<minval){
minval=arr[i];
}
totalSum=totalSum+arr[i];
}
let minsum=totalSum - maxval;
let maxsum=totalSum - minval;
console.log( minsum,maxsum);
}
Solution 13:[13]
Use build Math
methods to find max and min:
function miniMaxSum(arr) {
const min = Math.min(...arr);
const max = Math.max(...arr);
const sum = arr.reduce((a, b) => a + b);
console.log(sum - max, sum - min);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow