Find subset with elements that are furthest apart from eachother

前端 未结 4 2064
野的像风
野的像风 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 10:53

    $length = length($array);
    sort($array); //sorts the list in ascending order
    $differences = ($array << 1) - $array; //gets the difference between each value and the next largest value
    sort($differences);  //sorts the list in ascending order
    $max = ($array[$length-1]-$array[0])/$M; //this is the theoretical max of how large the result can be
    $result = array();
    for ($i = 0; i < $length-1; $i++){
        $count += $differences[i];
        if ($length-$i == $M - 1 || $count >= $max){ //if there are either no more coins that can be taken or we have gone above or equal to the theoretical max, add a point
            $result.push_back($count);
            $count = 0;
            $M--;
        }
    }
    return min($result)
    

    For the non-code people: sort the list, find the differences between each 2 sequential elements, sort that list (in ascending order), then loop through it summing up sequential values until you either pass the theoretical max or there arent enough elements remaining; then add that value to a new array and continue until you hit the end of the array. then return the minimum of the newly created array.

    This is just a quick draft though. At a quick glance any operation here can be done in linear time (radix sort for the sorts).

    For example, with 1, 4, 7, 100, and 200 and M=3, we get:

    $differences = 3, 3, 93, 100
    $max = (200-1)/3 ~ 67
    then we loop:
    $count = 3, 3+3=6, 6+93=99 > 67 so we push 99
    $count = 100 > 67 so we push 100
    min(99,100) = 99
    

    It is a simple exercise to convert this to the set solution that I leave to the reader (P.S. after all the times reading that in a book, I've always wanted to say it :P)

提交回复
热议问题