Maximum products of two integers in linear time in JavaScript


We are required to write a JavaScript function that takes in an array of Numbers with positive as well as negative numbers and returns the maximum products of two numbers in one traversal.

Let's write the code for this function −

Example

const arr = [-1, -3, -4, 2, 0, -5];
const arr2 = [2, 3, 5, 7, -7, 5, 8, -5];
const produce = arr => arr.reduce((acc, val) => acc*val);
const maximumProduct = (arr = []) => {
   const [first] = arr;
   if(!first){
      return 0;
   };
   const creds = arr.reduce((acc, val) => {
      const { min, max } = acc;
      if(val > max[0]){
         max[1] = max[0];
         max[0] = val;
         return acc;
      };
      if(val < min[0]){
         min[1] = min[0];
         min[0] = val;
         return acc;
      };
      if(val > max[1]){
         max[1] = val;
         return acc;
      };
      if(val < min[1]){
         min[1] = val;
         return acc;
      };
      return acc;
   }, {
      min: [first, first],
      max: [first, first]
   });
   const { max, min } = creds;
   return produce(max) > produce(min) ? produce(max) : produce(min);
};
console.log(maximumProduct(arr));
console.log(maximumProduct(arr2));

Output

The output in the console will be −

20
56

Updated on: 31-Aug-2020

83 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements