Maximum Product Difference Between Two Pairs

We will use sorting to tackle this problem. The idea is to sort the list and use the two largest numbers to form the first pair and two smallest numbers to form the second pair. This will ensure that the product difference is maximized.

Here’s the code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
class Solution:
    def maxProductDifference(self, nums: List[int]) -> int:
        nums.sort()  # Sort the numbers

        # Length of nums
        n = len(nums)

        # The first pair is the two smallest numbers
        pair1_product = nums[0] * nums[1]

        # The second pair is the two largest numbers
        pair2_product = nums[n-1] * nums[n-2]

        # The product difference is then
        product_difference = pair2_product - pair1_product

        return product_difference

The code starts by sorting the list of numbers. Then, it identifies the two smallest and two largest numbers to form two pairs. The product difference is computed by subtracting the product of the smallest pair from the product of the largest pair. The result is then returned. This code ensures the maximum product difference as per the problem’s constraints.