Find subset with K elements that are closest to eachother

后端 未结 6 903
误落风尘
误落风尘 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:10

    try the following:

    N = input()
    K = input()
    assert 2 <= N <= 10**5
    assert 2 <= K <= N
    a = some_unsorted_list
    a.sort()
    
    cur_diff = sum([abs(a[i] - a[i + 1]) for i in range(K - 1)])
    min_diff = cur_diff
    min_last_idx = K - 1
    for last_idx in range(K,N):
        cur_diff = cur_diff - \
                   abs(a[last_idx - K - 1] - a[last_idx - K] + \
                   abs(a[last_idx] - a[last_idx - 1])
        if min_diff > cur_diff:
            min_diff = cur_diff
            min_last_idx = last_idx
    

    From the min_last_idx, you can calculate the min_first_idx. I use range to preserve the order of idx. If this is python 2.7, it will take linearly more RAM. This is the same algorithm that you use, but slightly more efficient (smaller constant in complexity), as it does less then summing all.

提交回复
热议问题