The problem I am doing is on hackerrank, and I don't understand what I'm missing here feels like this should be working.
https://www.hackerrank.com/challenges/mini-max-sum/problem?isFullScreen=true
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.
Test Case 0:
arr = [1, 2, 3, 4, 5];
Test Case 1:
arr = [7, 69, 2, 221, 8974];
function miniMaxSum(arr) {
var temp = 0;
var mini = 0;
var max = 0;
for (let i = 0; i < arr.length; i ) {
temp = arr[i];
if (i == arr.length - 2) {
mini = temp;
}
}
max = temp - arr[0];
console.log(mini ' ' max);
}
Test case 1 fails
My output: 299 9266
Expected output: 299 9271
CodePudding user response:
In question and in test cases it does not say sorted array. You should sort it before putting in for. Add this before your loop arr = arr.sort((a,b) => a - b)
function miniMaxSum(arr) {
var temp = 0;
var mini = 0;
var max = 0;
arr = arr.sort((a,b) => a - b)
for (let i = 0; i < arr.length; i ) {
temp = arr[i];
if (i == arr.length - 2) {
mini = temp;
}
}
max = temp - arr[0];
console.log(mini, max)
}
CodePudding user response:
You're assuming that the input array is always sorted which is not true.
You can find out the maximum number and minimum number and then subtract them from the total sum.
function miniMaxSum(arr) {
let
maxNum = arr[0],
minNum = arr[0];
arr.forEach((a) => {
if (a > maxNum) {
maxNum = a;
}
if (a < minNum) {
minNum = a;
}
});
const totalSum = arr.reduce((s, a) => s a, 0);
console.log(totalSum - maxNum, totalSum - minNum);
}
miniMaxSum([4, 1, 3, 2, 5]);
You can also sort the array and then calculate the sum of the smallest n-1
values and the largest n-1
values, where n
is the length of the original array.
function miniMaxSum(arr) {
arr.sort((a, b) => a - b);
const minSum = arr.slice(0, arr.length - 1).reduce((s, n) => s n, 0);
const maxSum = arr.slice(1).reduce((s, n) => s n, 0);
console.log(minSum, maxSum);
}
miniMaxSum([4, 1, 3, 2, 5]);
CodePudding user response:
This is the solution which is passed all the tests. I hope it helps.
function miniMaxSum(arr) {
const total = arr.reduce((a,b) => a b , 0)
const sorted = arr.sort((a,b) => a -b)
const min = arr[0]
const max = arr.reverse()[0]
console.log(total-max, total-min)
}
let arr1 = [1,2,3,4,5]
let arr2 = [-2,56,874,255,32,478965]
console.log(miniMaxSum(arr1))
console.log(miniMaxSum(arr2))