How to useSorting and Multiplying in Javascript

In this approach, we are using the sorting approach. As we need to multiply the maximum element from both the arrays, initially, we sort the arrays in descending order, and then we multiply them with each other by taking the index of elements as the reference.

Example: This example shows the use of the above-explained approach.

Javascript




function maxSumProdUsingSortMult(inputArr1, inputArr2) {
    if (inputArr1.length !== inputArr2.length) {
        return -1;
    }
    inputArr1.sort((a, b) => b - a);
    inputArr2.sort((a, b) => b - a);
  
    let outputSum = 0;
    for (let i = 0; i < inputArr1.length; i++) {
        outputSum += inputArr1[i] * inputArr2[i];
    }
  
    return outputSum;
}
let array1 = [1, 2, 3];
let array2 = [5, 4, 6];
let result1 = 
    maxSumProdUsingSortMult(array1, array2);
console.log(result1);
  
let array3 = [4, 7, 5, 2];
let array4 = [2, 3, 2, 1];
let result2 = 
    maxSumProdUsingSortMult(array3, array4);
console.log(result2);


Output

32
41

Time Complexity: O(n log n)

Space Complexity: O(1)

JavaScript Program for Maximum Possible Sum of Products

In this article, we will find and print the maximum possible sum of products in the JavaScript language. We have two arrays, inputArr1, and inputArr2. Both these arrays contain positive numbers and the length of both arrays is similar. We have to write the function where every element in inputArr1 has to be multiplied with exactly one element in the inputArr2 array or vice versa, such that each element from both the arrays should appear exactly once and the sum of their multiplication should be maximum.

Examples:

Input: inputArr1[] = [1, 2, 3], inputArr2[] = [5, 4, 6]
Output: 32
Explanation: The maximum sum of product is obtained by 3*6+2*5+1*4 = 32

Table of Content

  • Using Greedy Algorithm in JavaScript
  • Using Sorting and Multiplying
  • Using JavaScript reduce method

Let’s go through all three approaches with the implementation.

Similar Reads

Approach 1: Using Greedy Algorithm in JavaScript

...

Approach 2: Using Sorting and Multiplying

Here, we are going to use the Greedy Algorithm to find the maximum possible sum of products. We are actually finding the maximum elements from the arrays and then we are multiplying these maximum elements with each other. Using the Infinity we are making sure that each value is used only once....

Approach 3: Using the JavaScript reduce method

...