Maximum Possible Sum of Products in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are given two arrays say, arr1 and arr2 of positive Numbers. The number of values in both the arrays are the same.

We are required to write a function that finds the maximum sum of products of their elements.

Each element in arr1 has to be multiplied with exactly one element in arr2 and vice versa such that each element of both the arrays appears exactly once and the sum of product produced is maximum.

For example: if,

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

Then a possible sum of product is −

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

Although, it may not be the largest sum.

Example

Following is the code −

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

Output

Following is the output in the console −

130
raja
Published on 16-Sep-2020 09:27:49
Advertisements