Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Maximum Possible Sum of Products in JavaScript
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.
Problem Understanding
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 = 30 + 7 + 27 + 40 + 16 = 120
Although, it may not be the largest sum.
Algorithm
To maximize the sum of products, we need to pair the largest elements from both arrays together. This is achieved by:
- Sorting both arrays in descending order
- Multiplying corresponding elements from sorted arrays
- Summing all the products
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
130
How It Works
Let's trace through the algorithm step by step:
const arr1 = [5,1,3,4,2];
const arr2 = [8,10,9,7,6];
// After sorting in descending order:
const a1Sorted = [5,4,3,2,1];
const a2Sorted = [10,9,8,7,6];
console.log("Sorted arr1:", a1Sorted);
console.log("Sorted arr2:", a2Sorted);
// Products: 5*10 + 4*9 + 3*8 + 2*7 + 1*6
console.log("Products: 5*10 + 4*9 + 3*8 + 2*7 + 1*6");
console.log("Result:", 50 + 36 + 24 + 14 + 6);
Sorted arr1: [ 5, 4, 3, 2, 1 ] Sorted arr2: [ 10, 9, 8, 7, 6 ] Products: 5*10 + 4*9 + 3*8 + 2*7 + 1*6 Result: 130
Alternative Approach Using Reduce
const maximumProductSum = (arr1, arr2) => {
if (arr1.length !== arr2.length) return false;
const sorted1 = [...arr1].sort((a, b) => b - a);
const sorted2 = [...arr2].sort((a, b) => b - a);
return sorted1.reduce((sum, val, index) => sum + val * sorted2[index], 0);
};
const arr1 = [5,1,3,4,2];
const arr2 = [8,10,9,7,6];
console.log("Maximum product sum:", maximumProductSum(arr1, arr2));
Maximum product sum: 130
Conclusion
To find the maximum sum of products, sort both arrays in descending order and multiply corresponding elements. This greedy approach ensures the largest values are paired together for optimal results.
