Given an integer array, find a triplet having the maximum product.

For example,

Input:  { -4, 1, -8, 9, 6 }
Output: The triplet having the maximum product is (-4, -8, 9)
 
Input:  { 1, 7, 2, -2, 5 }
Output: The triplet having the maximum product is (7, 2, 5)

Practice this problem

A naive solution would be to consider every triplet present in the array and compute the product of its elements. Finally, after processing all triplets, print the triplet having the maximum product. The time complexity of this solution would be O(n3), where n is the size of the input.

 
A better approach involves sorting the array. Then the triplet having the maximum product can be one of the two:

  1. The last three elements of the sorted array.
  2. First two elements and the last element of the sorted array (as the multiplication of two negative numbers results in a positive number).

The algorithm can be implemented as follows in C++, Java, and Python:

C++


Download  Run Code

Output:

Triplet is (-8, -4, 9)

Java


Download  Run Code

Output:

Triplet is (-8, -4, 9)

Python


Download  Run Code

Output:

Triplet is (-8, -4, 9)

The time complexity of the above solution is O(n.log(n)), which is better than the brute-force approach but is still costly for large input. The solution also modifies the input array, which might not be permitted.

Can we do better?

If we carefully analyze the above solution, we can see that it only uses the last three and the initial two sorted array elements. We can avoid that by finding the largest, second largest, third largest element, and the smallest, second smallest array element in linear time, as demonstrated below in C, Java, and Python:

C


Download  Run Code

Output:

Triplet is (-8, -4, 9)

Java


Download  Run Code

Output:

Triplet is (-8, -4, 9)

Python


Download  Run Code

Output:

Triplet is (-8, -4, 9)