Mini-Max Sum - 错误输出

Mini-Max Sum - Wrong output

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);
}

现在,如果数组只是 [1, 2, 3, 4, 5],输出应该是 10, 14。

我得到的输出是 15、16。

max 变量应该只添加从索引 1 开始的所有内容否?

还有 min 变量我不确定你是否能够做到这一点,但我的想法是从索引 0 开始初始化并向上移动到数组的末尾但负 1 索引。

我该如何纠正?

您需要确定 5 个元素中哪 4 个最大,5 个元素中哪 4 个最小 - 或者,等价地,确定哪个 元素是最大的最小,哪个一个元素最大,然后从所有5个元素的总和中减去它们:

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]);

另一种方法是使用切片并对数组的小端和大端求和。

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]));

只有当数字在数组中按升序排列时才有效

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]);

做起来很有趣 ;)