Minimize the Maximum Difference of Pairs

Updated on 12 June, 2025
Minimize the Maximum Difference of Pairs header image

Problem Statement

In this problem, you are provided with a 0-indexed integer array nums and an integer p. The task is to locate p pairs from the array such that the largest difference between any selected pair is as small as possible. Each index in the array should be used at most once in these pairs.

The difference for each pair (i, j) is calculated as the absolute value of the difference between their elements, |nums[i] - nums[j]|. The goal is to find and return the smallest value of the largest difference among all possible groups of p pairs, with the base assumption that the maximum difference of an empty set is zero.

Examples

Example 1

Input:

nums = [10,1,2,7,1,3], p = 2

Output:

1

Explanation:

The first pair is formed from the indices 1 and 4, and the second pair is formed from the indices 2 and 5.
The maximum difference is max(|nums[1] - nums[4]|, |nums[2] - nums[5]|) = max(0, 1) = 1. Therefore, we return 1.

Example 2

Input:

nums = [4,2,1,2], p = 1

Output:

0

Explanation:

Let the indices 1 and 3 form a pair. The difference of that pair is |2 - 2| = 0, which is the minimum we can attain.

Constraints

  • 1 <= nums.length <= 105
  • 0 <= nums[i] <= 109
  • 0 <= p <= (nums.length)/2

Approach and Intuition

The problem revolves around pairing elements in such a way that the maximum difference across pairs is minimized. To achieve this:

  1. Sort the Array: Start by sorting the array nums. Sorting helps group numbers that are close to each other, reducing the difference between paired indices.

  2. Pair Adjacent Elements: After sorting, the strategy is simple for creating pairs:

    • Pair the first element with the second, the third with the fourth, and so on. This method generally results in the smallest possible maximum difference because sorting ensures that adjacent elements are the closest in value.
  3. Calculate Maximum Difference: For each of these pairs, calculate their differences, then determine the maximum difference among them.

  4. Return the Result: The smallest of these maximum differences, computed across various valid pairing schemes, is the desired output.

This approach is driven by the intuition that elements which are closer together will, when paired, produce the smallest maximum differences. By sorting the array, we exploit this property systematically, ensuring that the largest differences are as small as possible. This method should meet the constraints efficiently, even for larger sizes of the input array.

Solutions

  • C++
  • Java
  • Python
cpp
class Solution {
public:
    // Function to calculate the number of valid differences
    int calculatePairs(vector<int>& elements, int maxDiff) {
        int position = 0, pairs = 0;
        while (position < elements.size() - 1) {
            // Increment the pair count when within the allowable difference
            if (elements[position + 1] - elements[position] <= maxDiff) {
                pairs++;
                position++;
            }
            position++;
        }
        return pairs;
    }

    int reduceMaxDifference(vector<int>& elements, int requiredPairs) {
        sort(elements.begin(), elements.end());
        int total = elements.size();
        int low = 0, high = elements[total - 1] - elements[0];

        while (low < high) {
            int midPoint = low + (high - low) / 2;
            
            // Search space adjustment
            if (calculatePairs(elements, midPoint) >= requiredPairs) {
                high = midPoint;
            } else {
                low = midPoint + 1;
            }
        }
        return low;
    }
};

The provided C++ code outlines a solution for minimizing the maximum difference between adjacent pairs in a sorted list of integers. The solution is encapsulated within a class named Solution that includes two functions: calculatePairs and reduceMaxDifference.

Functionality Breakdown:

  • calculatePairs(vector<int>& elements, int maxDiff)

    • This function aims to count the valid pairs (adjacent elements in the list) that have a difference less than or equal to maxDiff. Iterating through the list, it checks the difference between consecutive elements, counting each valid pair and adjusting the position index accordingly.
  • reduceMaxDifference(vector<int>& elements, int requiredPairs)

    • Initiates by sorting the input vector of integers. Then, using binary search, it adjusts the difference maxDiff to find the smallest maximum difference that allows for at least requiredPairs valid pairs.

Steps Involved in reduceMaxDifference:

  1. Sort the elements of the list.
  2. Define the initial search range for maxDiff: from 0 to the difference between the first and last elements.
  3. Conduct a binary search:
    1. Calculate the midpoint of the current search range.
    2. Using calculatePairs, determine whether the number of valid pairs with the current maxDiff (midpoint value) meets or exceeds the required pairs.
    3. Adjust the search range based on the comparison. If the count is sufficient, decrease the upper bound to reduce the maxDiff. If insufficient, increase the lower bound to explore larger differences.

The function finally returns the minimized maximum difference that allows fulfilling the requirement of the requiredPairs. This approach ensures the optimal solution, leveraging the efficiency of binary search and the logical count of pairing based on the defined maximum difference.

java
class Solution {
    // Calculate the number of pairs with difference no greater than a limit
    private int countPairs(int[] values, int limit) {
        int i = 0, pairs = 0;
        while (i < values.length - 1) {
            // Increment counter if pair meets the criteria, then skip to next possible pair
            if (values[i + 1] - values[i] <= limit) {
                pairs++;
                i++;
            }
            i++;
        }
        return pairs;
    }

    public int reduceMaximum(int[] values, int p) {
        Arrays.sort(values);
        int n = values.length;
        int min = 0, max = values[n - 1] - values[0];

        while (min < max) {
            int mid = min + (max - min) / 2;

            // Adjust search based on the number of valid pairs
            if (countPairs(values, mid) >= p) {
                max = mid;
            } else {
                min = mid + 1;
            }
        }
        return min;
    }
}

To minimize the maximum difference of pairs in an array of integers using Java, the task involves sorting the array and using a binary search technique to determine the smallest possible maximum difference that achieves a required number of pairs with a difference less than or equal to this maximum.

Follow these steps to unpack the logic and implementation:

  1. Define a helper function countPairs(int[] values, int limit) to calculate the number of pairs in the sorted array values where the difference of each pair does not exceed limit. Iteratively check consecutive elements and increment a count whenever the condition is met.

  2. Implement the main method reduceMaximum(int[] values, int p) which initially sorts the array and then defines the range [min, max] for the binary search; min starting at 0 and max as the difference between the largest and smallest values in the array.

  3. Apply binary search by setting the middle point mid and using the helper function to determine if there are at least p pairs with differences no greater than mid. Adjust min and max based on whether this condition is met.

  4. The binary search loops until min equals max, at which point min (or max) represents the minimized maximum difference that allows at least p pairs within that difference.

This implementation provides an efficient approach to the problem by leveraging sorting and binary search, optimizing the process of finding the required pair difference limit.

python
class Solution:
    def minimizeMaxDiff(self, numbers: List[int], min_pairs: int) -> int:
        numbers.sort()
        total_numbers = len(numbers)

        def validPairs(max_difference):
            position, valid_count = 0, 0
            while position < total_numbers - 1:
                if numbers[position + 1] - numbers[position] <= max_difference:
                    valid_count += 1
                    position += 1
                position += 1
            return valid_count
        
        low, high = 0, numbers[-1] - numbers[0]
        while low < high:
            middle = low + (high - low) // 2
            if validPairs(middle) >= min_pairs:
                high = middle
            else:
                low = middle + 1
        return low

The solution provided involves creating a function to minimize the maximum difference of pairs in a sorted list of numbers using a binary search approach.

  • Start by sorting the numbers list.
  • Implement a helper function, validPairs(max_difference), to determine how many pairs can be formed such that the difference between the numbers in each pair does not exceed max_difference.
    • Initialize two pointers, position and valid_count.
    • Use a while loop to iterate through the numbers list and count valid pairs.
  • Establish the binary search bounds with low as 0 and high as the difference between the maximum and minimum numbers in the list.
  • Conduct a binary search:
    • Calculate the middle index.
    • If the number of valid pairs for the mid value is greater than or equal to min_pairs, adjust the high boundary to middle.
    • Otherwise, adjust the low boundary to middle + 1.
  • The search concludes when low meets high, at which point low will represent the minimized maximum difference.

This method efficiently finds the smallest possible maximum difference for the specified number of valid pairs using sorting and binary search, ensuring optimal performance for large datasets.

Comments

No comments yet.