简体   繁体   中英

Greedy algorithm to pair numbers that minimizes the maximum sum

The input is a sequence of real numbers x1, x2, ..., x2n. We want to pair these numbers into n pairs. For the ith pair, (i = 1, 2, ..., n), let Si denote the sum of numbers in that pair. (For example if you pair x(2i−1) and x2i as the ith pair, Si = x(2i−1) + x2i). We want to pair these numbers so that Maxi[Si] is minimized. Design a greedy algorithm to solve this problem.


That's the question; my solution is to simply sort the numbers and pair the first-last elements and add-one/subtract-one index and repeat. The algorithm tries to optimize for each pair, so that makes it greedy. I'm just wondering if there's a linear time algorithm that will do this?

PS: This is not homework, but I understand this looks very much like it.

If you want to be greedy and approximate, you could run a fixed size window over the data, once, and only pair numbers within the window - the one at the left end of the window with any other one in the window - mark the one not at the left end, so you don't re-use it, and advance the window, so the one at the left end is not re-used. This is greedy in the sense of being only locally optimal. If you know the list is uniformly random it could be close, and it is linear, since sorting a list of constant length k is constant time, relative to N. With other knowledge about the distribution of the list you could use a variant that is still O(N) and only approximate.

No. There can't be a linear time algo to get this done for you. The input numbers can be in any order so you cant get the pairing done right away with min Maxi[Si]. Your current solution is simple and good.

Suggestions to improve on the running time:

You can create a Binary tree out of the input numbers (this takes O(nlog(n)) time). Do inorder traversal of the tree and create pairs from the (first+i, last-i) elements (i from 0 to n/2)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM