Minimize the Maximum Difference of Pairs

You are given a 0-indexed integer array nums and an integer p. Find p pairs of indices of nums such that the maximum difference amongst all the pairs is minimized. Also, ensure no index appears more than once amongst the p pairs.

For a pair of elements at indices i and j, the difference of this pair is |nums[i] - nums[j]|, where |x| represents the absolute value of x.

Return the minimum maximum difference among all p pairs. The maximum of an empty set is defined to be zero.

Example 1
Inputnums = [10,1,2,7,1,3], p = 2
Output1
The pairs can be formed from indices 1 and 4 with difference 0, and indices 2 and 5 with difference 1, so the maximum difference is 1.
Example 2
Inputnums = [4,2,1,2], p = 1
Output0
Indices 1 and 3 form a pair with difference |2 - 2| = 0, which is the minimum possible.

Constraints

  • 1 <= nums.length <= 10^5
  • 0 <= nums[i] <= 10^9
  • 0 <= p <= (nums.length)/2

Asked at 6 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate