1

I have two arrays that both contain $n$ elements (positive, non zero, not negative)
$\{x_1\dots x_n\}$
$\{y_1\dots y_n\}$

I want to pair them up optimally, one from each array, so that the pairs come out as even as possible, when paired up optimally. I want the difference between the highest sum of pair values and the lowest such sum to be as small as possible.
I know there are brute force ways but they take $O(n^2)$ time, and I want the time complexity to be low, say $O(n^{1.5})$ or lower.

My approach is to sort one of the arrays in ascending order, and one in descending order and pair them up.
How would I go about making sure they are actually paired optimally so that difference between the smallest sum and the highest sum among pairs is as small as possible?

greybeard
  • 1,172
  • 2
  • 9
  • 24
Ally Zane
  • 11
  • 2

2 Answers2

2

my approach is to sort one of the arrays in ascending order, and one in descending order and pair them up

Yes, that's optimal.

You pair the smallest x-value $x$ with the largest y-value $Y$. Suppose that's a mistake, i.e., you end up with a solution worse than some optimal better solution which pairs $x$ with some other $y \le Y$ (and thus pairs $Y$ with some other $X \ge x$). So that optimal solution has sums $x+y$ and $X+Y$. Now modify that optimal solution to use $x+Y$ and $X+y$ instead. We have $x+y \le x+Y,X+y \le X+Y$, so replacing $x+y$ and $X+Y$ with $x+Y$ and $X+y$ doesn't extend the range and thus the solution stays optimal. Meaning there is an optimal solution that does pair $x$ and $Y$. You're good.

Kelly Bundy
  • 530
  • 2
  • 16
0

If your goal is to minimize the maximum absolute difference of each pair, I suggest trying to explore greedy algorithms. In particular, suppose the arrays are presented in sorted order, and suppose for the moment that there are no duplicates, so $x_1 < x_2 < \cdots$ and $y_1 < y_2 < \cdots$. Suppose $x_1 < y_1$. What can you say about which element $x_1$ should be paired with? Can you make a greedy choice and proceed, and prove that this will give an optimal algorithm?

D.W.
  • 167,959
  • 22
  • 232
  • 500