A straightforward solution is to evaluate every pair of elements and keep track of the maximum product. Below is the implementation of this simple solution.
publicclassSolution {
publicint[]maxProductPair(int[] nums) {
if (nums.length< 2) {
returnnewint[] {};
}
Arrays.sort(nums); // Sort the array in ascending orderint product1 = nums[0]* nums[1]; // Product of the first two elementsint product2 = nums[nums.length- 1]* nums[nums.length- 2]; // Product of the last two elementsif (product1 > product2) {
returnnewint[] {nums[0], nums[1]};
} else {
returnnewint[] {nums[nums.length- 2], nums[nums.length- 1]};
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
classSolution:
defmaxProductPair(self, nums):
if len(nums) <2:
return []
nums.sort() # Sort the array in ascending order product1 = nums[0] * nums[1] # Product of the first two elements product2 = nums[-1] * nums[-2] # Product of the last two elementsif product1 > product2:
return [nums[0], nums[1]]
else:
return [nums[-2], nums[-1]]
Method 3 - Using Second Max and Second Min element#
An efficient solution can address the problem in a single traversal of the input array. The idea is to track the following four values during the traversal:
The largest positive value.
The second largest positive value.
The smallest (most negative) value.
The second smallest (most negative) value.
At the end of the traversal, compare the products of the two positive values and the two negative values and return the higher product. Below is the implementation of this idea.
classSolution:
defmaxProductPair(self, nums):
if len(nums) <2:
return []
# Initialize variables to track the required values max1 = max2 = float('-inf')
min1 = min2 = float('inf')
for num in nums:
# Update the largest and second largest positive valuesif num > max1:
max2 = max1
max1 = num
elif num > max2:
max2 = num
# Update the smallest and second smallest negative valuesif num < min1:
min2 = min1
min1 = num
elif num < min2:
min2 = num
# Compare products and return the pair with the highest productif max1 * max2 > min1 * min2:
return [max1, max2]
else:
return [min1, min2]