在 JavaScript 中返回数组中 n 个数字的最大可能乘积

javascriptweb developmentfront end technologyobject oriented programming更新于 2024/1/9 22:36:17

我们需要编写一个 JavaScript 函数,该函数将数字数组作为第一个参数,将数字(例如 n)作为第二个参数。

我们的函数应该计算并返回数组中 n 个数字的最大可能乘积。

示例

其代码为 −

const getHighestProduct = (arr, num) => {
   let prod = 1;
   const sorter = (a, b) => a - b;
   arr.sort(sorter);
   if (num > arr.length || num & 2 && arr[arr.length - 1] < 0) {
      return;
   };
   if (num % 2) {
      prod = arr.pop();
      num--;
   };
   while (num) {
      prod *= arr[0] * arr[1] > arr[arr.length - 2] * arr[arr.length - 1]
      ? arr.shift() * arr.shift() : arr.pop() * arr.pop();
      num -= 2;
   };
   return prod;
}
console.log(getHighestProduct([1, 10, -5, 1, -100], 3));
console.log(getHighestProduct([3, 4, 5, 6, 7], 3));
console.log(getHighestProduct([3, 4, -5, -6, -7], 3));

输出

控制台中的输出将是 −

5000
210
168

相关文章


有用资源