Maximum Product of Two Numbers in a List of Integers in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of integers as the first and the only argument.

The function should find the maximum product that can be achieved multiplying any two elements of the array. The condition for us is that we have to do this in linear time and constant space.

For example −

If the input array is −

const arr = [3, 9, 2, 1, 0];

Then the output should be −

const output = 27;

because it’s the greatest product and can be achieved by multiplying 3 and 9.

Example

Following is the code −

const arr = [3, 9, 2, 1, 0];
const maxPairProduct = (arr = []) => {
   let c = Infinity, d = c;
   let a = -Infinity - 1, b = a;
   for (const n of arr) {
      if(n >= a){
         b = a;
         a = n;
      }else if(n >= b){
         b = n;
      };
      if(n <= d){
         c = d;
         d = n;
      }else if(n <= c){
         c = n;
      };
   };
   return Math.max(a * b, c * d);
};
console.log(maxPairProduct(arr));

Output

Following is the console output −

27
raja
Published on 23-Jan-2021 06:47:53
Advertisements