Given an integer array, find the maximum product of two integers in it.

For example, consider array {-10, -3, 5, 6, -2}. The maximum product is the (-10, -3) or (5, 6) pair.

Practice this problem

 
A naive solution is to consider every pair of elements and calculate their product. Update the maximum product found so far if the product of the current pair is greater. Finally, print the elements involved in the maximum product. This is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

Pair is (-10, -3)

Java


Download  Run Code

Output:

Pair is (-10, -3)

Python


Download  Run Code

Output:

Pair is (-10, -3)

The time complexity of the above solution is O(n2) and doesn’t require any extra space, where n is the size of the input.

 
The time complexity can be improved by sorting the array. Then the result is the maximum of the following:

  1. The product of maximum and second maximum integer in the array (i.e., the last two elements in a sorted array).
  2. The product of minimum and second minimum integers in the array (i.e., the first two elements in the sorted array).

Following is the implementation of the above algorithm in C, Java, and Python:

C


Download  Run Code

Output:

Pair is (-20, -10)

Java


Download  Run Code

Output:

Pair is (-20, -10)

Python


Download  Run Code

Output:

Pair is (-20, -10)

The time complexity of the above solution is O(n.log(n)) and doesn’t require any extra space.

 
We can solve this problem in linear time as we need the only maximum, second maximum, minimum, and second minimum elements to solve this problem. We can compute all these in only a single traversal of the array, which accounts for O(n) time complexity. This approach is demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

Pair is (-10, -3)

Java


Download  Run Code

Output:

Pair is (-10, -3)

Python


Download  Run Code

Output:

Pair is (-10, -3)

Exercise: Find the maximum product of three integers in an array