Find subset with elements that are furthest apart from eachother

前端 未结 4 2069
野的像风
野的像风 2021-02-03 10:39

I have an interview question that I can\'t seem to figure out. Given an array of size N, find the subset of size k such that the elements in the subset are the furthest apart fr

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-03 11:15

    The basic idea is right, I think. You should start by sorting the array, then take the first and the last elements, then determine the rest.

    I cannot think of a polynomial algorithm to solve this, so I would suggest one of the two options.

    One is to use a search algorithm, branch-and-bound style, since you have a nice heuristic at hand: the upper bound for any solution is the minimum size of the gap between the elements picked so far, so the first guess (evenly spaced cells, as you suggested) can give you a good baseline, which will help prune most of the branches right away. This will work fine for smaller values of k, although the worst case performance is O(N^k).

    The other option is to start with the same baseline, calculate the minimum pairwise distance for it and then try to improve it. Say you have a subset with minimum distance of 10, now try to get one with 11. This can be easily done by a greedy algorithm -- pick the first item in the sorted sequence such that the distance between it and the previous item is bigger-or-equal to the distance you want. If you succeed, try increasing further, if you fail -- there is no such subset.

    The latter solution can be faster when the array is large and k is relatively large as well, but the elements in the array are relatively small. If they are bound by some value M, this algorithm will take O(N*M) time, or, with a small improvement, O(N*log(M)), where N is the size of the array.

    As Evgeny Kluev suggests in his answer, there is also a good upper bound on the maximum pairwise distance, which can be used in either one of these algorithms. So the complexity of the latter is actually O(N*log(M/k)).

提交回复
热议问题