Skip to content

2616. Minimize the Maximum Difference of Pairs 👍

  • Time: $O(\texttt{sort}) + O(n\log (\max(\texttt{nums}) - \min(\texttt{nums})))$
  • Space: $O(\texttt{sort})$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Solution {
 public:
  int minimizeMax(vector<int>& nums, int p) {
    ranges::sort(nums);

    int l = 0;
    int r = nums.back() - nums.front();

    while (l < r) {
      const int m = (l + r) / 2;
      if (numPairs(nums, m) >= p)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

 private:
  // Returns the number of pairs that can be obtained if the difference between
  // each pair <= `maxDiff`.
  int numPairs(const vector<int>& nums, int maxDiff) {
    int pairs = 0;
    for (int i = 1; i < nums.size(); ++i)
      // Greedily pair nums[i] with nums[i - 1].
      if (nums[i] - nums[i - 1] <= maxDiff) {
        ++pairs;
        ++i;
      }
    return pairs;
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
  public int minimizeMax(int[] nums, int p) {
    Arrays.sort(nums);

    int l = 0;
    int r = nums[nums.length - 1] - nums[0];

    while (l < r) {
      final int m = (l + r) / 2;
      if (numPairs(nums, m) >= p)
        r = m;
      else
        l = m + 1;
    }

    return l;
  }

  // Returns the number of pairs that can be obtained if the difference between each
  // pair <= `maxDiff`.
  private int numPairs(int[] nums, int maxDiff) {
    int pairs = 0;
    for (int i = 1; i < nums.length; ++i)
      // Greedily pair nums[i] with nums[i - 1].
      if (nums[i] - nums[i - 1] <= maxDiff) {
        ++pairs;
        ++i;
      }
    return pairs;
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class Solution:
  def minimizeMax(self, nums: List[int], p: int) -> int:
    nums.sort()

    def numPairs(maxDiff: int) -> int:
      """
      Returns the number of pairs that can be obtained if the difference between
      each pair <= `maxDiff`.
      """
      pairs = 0
      i = 1
      while i < len(nums):
        # Greedily pair nums[i] with nums[i - 1].
        if nums[i] - nums[i - 1] <= maxDiff:
          pairs += 1
          i += 2
        else:
          i += 1
      return pairs

    return bisect.bisect_left(
        range(0, nums[-1] - nums[0]), p,
        key=lambda m: numPairs(m))