Find subset with K elements that are closest to eachother

后端 未结 6 905
误落风尘
误落风尘 2020-12-30 04:44

Given an array of integers size N, how can you efficiently find a subset of size K with elements that are closest to each other?

Le

6条回答
  •  死守一世寂寞
    2020-12-30 05:15

    My initial solution was to look through all the K element window and multiply each element by m and take the sum in that range, where m is initialized by -(K-1) and incremented by 2 in each step and take the minimum sum from the entire list. So for a window of size 3, m is -2 and the values for the range will be -2 0 2. This is because I observed a property that each element in the K window add a certain weight to the sum. For an example if the elements are [10 20 30] the sum is (30-10) + (30-20) + (20-10). So if we break down the expression we have 2*30 + 0*20 + (-2)*10. This can be achieved in O(n) time and the entire operation would be in O(NK) time. However it turns out that this solution is not optimal, and there are certain edge cases where this algorithm fails. I am yet to figure out those cases, but shared the solution anyway if anyone can figure out something useful from it.

    for(i = 0 ;i <= n - k;++i)
    {
        diff = 0;
        l = -(k-1);
        for(j = i;j < i + k;++j)
        {
            diff += a[j]*l;
            if(min < diff)
                break;
            l += 2;
        }
        if(j == i + k && diff > 0)
        min = diff;
    }
    

提交回复
热议问题