The task is to find the maximum product difference between two pairs in an integer array. The product difference between two pairs (a, b)
and (c, d)
is defined as (a * b) - (c * d)
.
Given an integer array nums
, choose four distinct indices i, j, k, l
such that the product difference between pairs (nums[i], nums[j])
and (nums[k], nums[l])
is maximized.
Return the maximum such product difference.
nums
contain negative numbers?nums
?For the problem, let’s assume:
To find the maximum product difference:
nums
.def maxProductDifference(nums):
# Step 1: Sort the array
nums.sort()
# Step 2: Compute the product of the two largest elements
max_product = nums[-1] * nums[-2]
# Step 3: Compute the product of the two smallest elements
min_product = nums[0] * nums[1]
# Step 4: Calculate the product difference
product_difference = max_product - min_product
return product_difference
# Example usage:
nums = [5, 6, 2, 7, 4]
print(maxProductDifference(nums)) # Output: 34
Thus, the overall time complexity is (O(n \log n)).
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?