How to compute the minimum possible sum? Given two sets of having equal number of unique numbers we need to find the minimum possible sum.
Where sum is the square of the difference of the number taken one at a time as a pair and each number can be used only once.
Example: if we have A[3,5,8] and B[4,6,10]
here one possible sum could be,
$$(3-4)^2 +(5-6)^2+(8-10)^2=6$$
 A: You should sort both lists in increasing order so that $A=[x_1,x_2,...,x_n]$ and $B=[y_1,y_2,...,y_n]$ are sorted with $x_1<x_2<...<x_n$ and $y_1<y_2<...<y_n$. Then the minimal squared sum is
$$
S_{\min}=(x_1-y_1)^2+(x_2-y_2)^2+...+(x_n-y_n)^2
$$

To see this, consider the somewhat simpler case of $n=2$ with $A=[x,x+s]$ and $B=[y,y+t]$ for some positive integers $s,t$. Here we only have two candidates for the sums, namely
$$
S_1=(x-y)^2+((x+s)-(y+t))^2=2(x-y)^2+2(x-y)(s-t)+(s-t)^2
$$
and
$$
S_2=(x-(y+t))^2+((x+s)-y)^2=2(x-y)^2+2(x-y)(s-t)+s^2+t^2
$$
And we see that $S_2-S_1=2st>0$ so $S_1$ following the ordering of $A$ and $B$ is minimal for the case $n=2$.

Now let us turn to the general case for an arbitrary number of elements $n\in\mathbb N$. Suppose $A$ has been sorted so that $x_1<x_2<...<x_n$ whereas $y_1,y_2,...,y_n$ are not sorted. Then we may identify an inversion ie. $y_i>y_{i+1}$, but then the $n=2$ case tells us that switching $y_i$ and $y_{i+1}$ improves the squared sum. Continuing like this, eventually $B$ has been sorted, improving the squared sum for each time we eliminate an inversion.
