Find subset with elements that are furthest apart from eachother

前端 未结 4 2113
野的像风
野的像风 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条回答
  •  萌比男神i
    2021-02-03 11:07

    This can be solved in polynomial time using DP.

    The first step is, as you mentioned, sort the list A. Let X[i,j] be the solution for selecting j elements from first i elements A.

    Now, X[i+1, j+1] = max( min( X[k,j], A[i+1]-A[k] ) ) over k<=i.

    I will leave initialization step and memorization of subset step for you to work on.

    In your example (1,2,6,10) it works the following way:

        1    2   6   10
    1   -    -   -    -
    2   -    1   5    9
    3   -    -   1    4
    4   -    -   -    1
    

提交回复
热议问题