Getting the lowest possible sum from numbers' difference

后端 未结 10 1329
滥情空心
滥情空心 2020-12-23 22:19

I have to find the lowest possible sum from numbers\' difference.

Let\'s say I have 4 numbers. 1515, 1520, 1500 and 1535. The lowest sum of difference is 30, becaus

10条回答
  •  情歌与酒
    2020-12-23 22:32

    I assume the general problem is this: given a list of 2n integers, output a list of n pairs, such that the sum of |x - y| over all pairs (x, y) is as small as possible.

    In that case, the idea would be:

    • sort the numbers
    • emit (numbers[2k], numbers[2k+1]) for k = 0, ..., n - 1.

    This works. Proof:

    Suppose you have x_1 < x_2 < x_3 < x_4 (possibly with other values between them) and output (x_1, x_3) and (x_2, x_4). Then

    |x_4 - x_2| + |x_3 - x_1| = |x_4 - x_3| + |x_3 - x_2| + |x_3 - x_2| + |x_2 - x_1| >= |x_4 - x_3| + |x_2 - x_1|.

    In other words, it's always better to output (x_1, x_2) and (x_3, x_4) because you don't redundantly cover the space between x_2 and x_3 twice. By induction, the smallest number of the 2n must be paired with the second smallest number; by induction on the rest of the list, pairing up smallest neighbours is always optimal, so the algorithm sketch I proposed is correct.

提交回复
热议问题