Maximum Product Difference Between Two Pairs

Updated on 10 June, 2025
Maximum Product Difference Between Two Pairs header image

Problem Statement

The concept of "product difference" is defined for two pairs of numbers (a, b) and (c, d) as (a * b) - (c * d). Given an integer array nums, the goal is to find four distinct indices such that the product difference between the two pairs formed by these indices is maximized. In simpler terms, you need to select indices w, x, y, and z from the array such that the difference between the product of nums[w] and nums[x], and that of nums[y] and nums[z] is the largest possible. The function should return this maximum product difference.

Examples

Example 1

Input:

nums = [5,6,2,7,4]

Output:

34

Explanation:

We can choose indices 1 and 3 for the first pair (6, 7) and indices 2 and 4 for the second pair (2, 4).
The product difference is (6 * 7) - (2 * 4) = 34.

Example 2

Input:

nums = [4,2,5,9,7,4,8]

Output:

64

Explanation:

We can choose indices 3 and 6 for the first pair (9, 8) and indices 1 and 5 for the second pair (2, 4).
The product difference is (9 * 8) - (2 * 4) = 64.

Constraints

  • 4 <= nums.length <= 104
  • 1 <= nums[i] <= 104

Approach and Intuition

  1. To maximize the product difference (a * b) - (c * d), aim for (a * b) to be as large as possible and (c * d) to be as small as possible. This observation is foundational for our strategy.

  2. Extract the two largest and the two smallest elements from nums. This is because the product of the two largest numbers will yield the highest possible product from the array, and similarly, the product of the two smallest numbers will tend to be the smallest (or most negative if negatives were possible, but constraints forbid negatives).

  3. How do we efficiently find these numbers?

    • Sort the array: Once nums is sorted, the two largest elements will be the last two elements of the sorted array, and the two smallest will be the first two elements.
    • Calculate based on the sorted positions: If we denote sorted nums as nums_sorted, then:
      • The two largest numbers can be accessed as nums_sorted[-1] and nums_sorted[-2].
      • The two smallest numbers can be accessed as nums_sorted[0] and nums_sorted[1].
    • Compute the product difference: Using the four identified numbers, compute (nums_sorted[-1] * nums_sorted[-2]) - (nums_sorted[0] * nums_sorted[1]).
  4. Given the constraints (4 <= nums.length <= 104 and 1 <= nums[i] <= 104), this method is efficient. Sorting the array will take O(n log n), which is reasonable for the input size limit. This approach ensures that we automatically respect the condition of choosing four distinct indices since the largest and smallest pairs are distinct by definition in sorted order.

By focusing on maximizing the primary product and minimizing the secondary product via sorting and strategic selection, we can robustly determine the maximum product difference achievable.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    int maximumProductDifference(vector<int>& nums) {
        int largest = 0;
        int secondLargest = 0;
        int tiniest = INT_MAX;
        int secondTiniest = INT_MAX;
        
        for (int value : nums) {
            if (value > largest) {
                secondLargest = largest;
                largest = value;
            } else {
                secondLargest = max(secondLargest, value);
            }
            
            if (value < tiniest) {
                secondTiniest = tiniest;
                tiniest = value;
            } else {
                secondTiniest = min(secondTiniest, value);
            }
        }
        
        return largest * secondLargest - tiniest * secondTiniest;
    }
};

The provided C++ code defines a solution for calculating the maximum product difference between two pairs within an integer array. The function maximumProductDifference calculates this by first identifying the two largest and two smallest elements in the array.

Here's a breakdown of how the code achieves this:

  • Initializes four integer variables: largest, secondLargest set to 0, and tiniest, secondTiniest set to INT_MAX to hold the largest and smallest values respectively.
  • Iterates through each integer in the nums array using a for loop. For each element:
    • Updates largest and secondLargest if the current value is greater than largest. If not, updates secondLargest if it's greater than the current value of secondLargest.
    • Updates tiniest and secondTiniest if the current value is less than tiniest. If not, updates secondTiniest if it is greater than the current value of secondTiniest.
  • Finally, it calculates the product difference by multiplying largest with secondLargest and subtracting the product of tiniest and secondTiniest from it.

This algorithm effectively and efficiently finds the required elements to determine the maximum product difference without sorting the array, thus operating in linear time complexity O(n). This method ensures optimal performance even for large input arrays.

java
class Solution {
    public int maxProductDifference(int[] values) {
        int max1 = 0;
        int max2 = 0;
        int min1 = Integer.MAX_VALUE;
        int min2 = Integer.MAX_VALUE;
        
        for (int value : values) {
            if (value > max1) {
                max2 = max1;
                max1 = value;
            } else {
                max2 = Math.max(max2, value);
            }
            
            if (value < min1) {
                min2 = min1;
                min1 = value;
            } else {
                min2 = Math.min(min2, value);
            }
        }
        
        return max1 * max2 - min1 * min2;
    }
}

The provided Java code solves the problem of finding the maximum product difference between two pairs of elements in an array. The approach involves calculating the maximum product of two values and the minimum product of two other values from the given array, then computing the difference of these two products.

  • Start by initializing two sets of variables to keep track of the highest values (max1, max2) and the lowest values (min1, min2).
  • Iterate through each element in the array:
    • Update max1 and max2 to always contain the largest and second-largest values in the array.
    • Similarly, keep min1 and min2 updated to hold the smallest and second-smallest values.
  • After exiting the loop, calculate the products max1 * max2 and min1 * min2.
  • The function returns the result by subtracting the product of the smallest pair from the product of the largest pair, yielding the maximum product difference.

This method ensures that one captures all necessary comparisons in one traversal of the array, achieving an optimal solution in terms of time and space efficiency.

python
class Solution:
    def computeMaxProductDifference(self, values: List[int]) -> int:
        max1 = 0
        max2 = 0
        min1 = float('inf')
        min2 = float('inf')
        
        for value in values:
            if value > max1:
                max2 = max1
                max1 = value
            elif value > max2:
                max2 = value
                
            if value < min1:
                min2 = min1
                min1 = value
            elif value < min2:
                min2 = value
        
        return max1 * max2 - min1 * min2

This Python solution is designed to find the maximum product difference between two pairs of numbers from a given list. The main concept is to identify the two highest and two lowest values from the list in a single iteration. This process ensures efficiency, saving time by avoiding multiple full scans of the array.

The strategy can be summarized as follows:

  • Initialize four variables — two to store the maximum values (max1, max2) and two to store the minimum values (min1, min2). Set max1 and max2 to zero and min1 and min2 to infinity (float('inf')), which acts as a placeholder until the actual list values are checked.
  • Iterate over each value in the list values:
    • Update max1 and max2 if you find a value greater than max1 or max2.
    • Similarly, update min1 and min2 if a value less than min1 or min2 is found.

After identifying these four critical values, compute the desired result by calculating the expression max1 * max2 - min1 * min2.

This method is not only direct but also optimal with an O(n) complexity, as it runs through the list a single time, performing constant time checks and updates during each iteration. This ensures that the program is suitable for large datasets.

Comments

No comments yet.