JavaScript 中最大可能的乘积和

javascriptweb developmentfront end technologyobject oriented programming更新于 2025/12/6 14:04:17

我们给出了两个正数数组,即 arr1 和 arr2。两个数组中的值的数量相同。

我们需要编写一个函数来查找它们元素乘积的最大和。

arr1 中的每个元素必须与 arr2 中的一个元素相乘,反之亦然,使得两个数组的每个元素都恰好出现一次,并且产生的乘积和最大。

例如:如果,

arr1 = [5,1,3,4,2] 和,
arr2 = [8,10,9,7,6]

那么可能的乘积和是 −

5*6 + 1*7 + 3*9 + 4*10 + 2*8

尽管它可能不是最大的和。

示例

以下是代码 −

const arr1 = [5,1,3,4,2];
const arr2 = [8,10,9,7,6];
const sorter = (a, b) => b - a;
const greatestProduct = (a1, a2) => {
   if(a1.length !== a2.length){
      return false;
   };
   const a1Sorted = a1.slice().sort(sorter);
   const a2Sorted = a2.slice().sort(sorter);
   let res = 0;
   for(let i = 0; i < a1.length; i++){
      res += (a1Sorted[i] * a2Sorted[i]);
   };
   return res;
};
console.log(greatestProduct(arr1, arr2));

输出

以下是控制台中的输出 −

130

相关文章


有用资源