Sorting Approach

An alternative approach is to sort the array using sort() method ( in a non-decreasing order. after sorting of the array, the final two elements (largest in magnitude) can be considered as the possible pair with the maximum product.

Example: This JavaScript code finds the pair of integers with the maximum product in an array by sorting it first, then comparing products of the first two and last two elements to determine the maximum pair.

JavaScript
function findMaxProductPair(arr) {
    const n = arr.length;
    if (n < 2) {
        return null;
    }

    arr.sort((a, b) => a - b);

    const product1 = arr[0] * arr[1];
    const product2 = arr[n - 1] * arr[n - 2];
    return product1 > product2 ?
        [arr[0], arr[1]] : [arr[n - 1], arr[n - 2]];
}

const arr = [1, 2, -6, 3, -7];
const maxPair = findMaxProductPair(arr);

if (maxPair !== null) {
    console.log("Maximum product pair: "
        + maxPair[0] + " and " + maxPair[1]);
    console.log("Maximum product: "
        + (maxPair[0] * maxPair[1]));
} else {
    console.log("No pair found.");
}

Output
Maximum product pair: -7 and -6
Maximum product: 42

Time Complexity: O(nlog n)

Auxiliary Space: O(1)

Find the Maximum Product of Two Integers in the Array using JavaScript ?

Given an array of integers, we need to find the maximum product of two integers in the array using JavaScript.

Example:

Input: arr[] = {4, 6, 8, -5, -4, 4}  
Output: 48, {6,8}
Explanation: Maximum product is 48, which is obtained by
multiplying the numbers 6 and 8 of the array.

Table of Content

  • Brute Force Approach
  • Sorting Approach
  • Efficient Approach

Similar Reads

Brute Force Approach

The simplest approach to finding out which pair in an array of integers has the maximum product is to calculate the products of each pair by iterating through every possible pairing....

Sorting Approach

An alternative approach is to sort the array using sort() method ( in a non-decreasing order. after sorting of the array, the final two elements (largest in magnitude) can be considered as the possible pair with the maximum product....

Efficient Approach

An optimal approach must be taken into consideration when handling arrays containing negative integers. We can determine which pair in the array provides the maximum product by finding the maximum and minimum elements....