Mini-Max Sum - Wrong output

Viewed 101

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.

For example, if the array is [1, 3, 5, 7, 9]. Our minimum sum is 1 + 3 + 5 + 7 = 16 and our maximum sum is 3 + 5 + 7 + 9 = 24.

function miniMaxSum(arr) {
   let max = arr.reduce((a, b) => a + b, 1);

   let min = arr.reduce((a, b) => a + b, 0, arr.length - 1);

   console.log(min, max);
}

Right now, the output should be 10, 14 if the array is just [1, 2, 3, 4, 5].

The output I am getting is 15, 16.

The max variable should just add everything starting from index 1 no?

And the min variable I'm not sure if you're able to do this, but my thinking was initialize the starting at index 0 and go up to the end of the array but minus 1 index.

How can I correct this?

3 Answers

You need to identify which 4 of the 5 elements are the largest, and which 4 of the 5 elements are the smallest - or, equivalently, identify which one element is the smallest, and which one element is the largest, and subtract those from the sum of all 5 elements:

function miniMaxSum(arr) {
  // fullSum: sum of all items in the array
  const fullSum = arr.reduce((a, b) => a + b, 0);
  // Find smallest value in array
  const min = Math.min(...arr);
  // Find largest value in array
  const max = Math.max(...arr);

  console.log(fullSum - max, fullSum - min);
}
miniMaxSum([1, 3, 5, 7, 9]);
miniMaxSum([1, 2, 3, 4, 5]);

Another approach is to use slice and sum the small and and the large end of the array.

function miniMax(arr) {
  const sum = a => a.reduce((a, b) => a + b, 0);

  // we can skip the sort if we know the input is sorted, but just in case
  const sorted = arr.sort((a,b) => a-b)
  
  const min = sum(sorted.slice(0, sorted.length-1))  // sum the small end of the array
  const max = sum(sorted.slice(1))  // sum the large end of the array

  return { min, max }
}

console.log(miniMax([1, 3, 5, 7, 9]));
console.log(miniMax([1, 2, 3, 4, 5]));

This only works if the numbers are listed in ascending order in the array

function miniMaxSum(arr)
  {
  let max = arr.reduce((a,c,i)=>i?a+c:0, 0);
  let min = arr.reduce((a,c,i,t)=>i?a+t[i-1]:0, 0);
  document.write(`${JSON.stringify(arr)} -> min: ${min}, max: ${max} <br>`);
}

miniMaxSum([1, 3, 5, 7, 9]);

miniMaxSum([1, 2, 3, 4, 5]);

It was fun to do ;)

Related