Reputation: 79
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.
the expected Output is
299 9271
my output is
299 9266
the input is
7 69 2 221 8974
this is my function
function miniMaxSum(arr) {
let panjang = arr.length,
max = arr.slice(0, panjang-1),
min = arr.slice(1, panjang),
maxSum = max.reduce((total, item) => total+item),
minSum = min.reduce((total, item) => total+item);
process.stdout.write(`${maxSum} ${minSum}`);
}
can someone help me please?
Upvotes: 0
Views: 127
Reputation: 370949
By slicing from 0 to 4, and from 1 to 5, you're assuming that the array is already sorted, and that the items at index 0 and 5 are the maximum and minimum - which they aren't.
Either sort the array first, or use Math.max
/ Math.min
to identify the smallest and largest, and subtract from the sum.
const arr = [7, 69, 2, 221, 8974];
const sum = arr.reduce((a, b) => a + b, 0);
const min = Math.min(...arr);
const max = Math.max(...arr);
console.log(sum - max, sum - min);
Upvotes: 3