Find the minimum number of elements required so that their sum equals or exceeds S

前端 未结 5 1227
你的背包
你的背包 2021-02-05 11:46

I know this can be done by sorting the array and taking the larger numbers until the required condition is met. That would take at least nlog(n) sorting time.

Is there a

5条回答
  •  盖世英雄少女心
    2021-02-05 12:48

    One improvement (asymptotically) over Theta(nlogn) you can do is to get an O(n log K) time algorithm, where K is the required minimum number of elements.

    Thus if K is constant, or say log n, this is better (asymptotically) than sorting. Of course if K is n^epsilon, then this is not better than Theta(n logn).

    The way to do this is to use selection algorithms, which can tell you the ith largest element in O(n) time.

    Now do a binary search for K, starting with i=1 (the largest) and doubling i etc at each turn.

    You find the ith largest, and find the sum of the i largest elements and check if it is greater than S or not.

    This way, you would run O(log K) runs of the selection algorithm (which is O(n)) for a total running time of O(n log K).

提交回复
热议问题