I would like to get the top X elements of an array that sum-up to at least a given sum without sorting the whole array beforehand in linear time. I think its not possible to get linear time in all cases but at least in my input arrays i have roughly 1% of the elements that make out 99% of the sum. And i need to identify those correctly. I don't know know if it helps but the sum of all elements is always 1.
I have already implemented it with a sorted array but that blows up the complexity of my algorithm. Afterwards I have already looked into the top-k algorithm and the knapsack algorithm but they do not allow a flexible x elements dependet on a given minimum sum.
Input Array: [0.1, 0.2, 0.4, 0.05, 0.01, 0.01, 0.01, 0.02, 0.15, 0.05]
Example 1:
Given Sum: 0.8
Expected output [0.1, 0.2, 0.4, 0.15, ] --> Sum 0.85 but only top 4 elements
Example 2:
Given Sum: 0.95
Expected output [0.1, 0.2, 0.4, 0.15, 0.05, 0.05 ] --> Sum 0.95 but only top 6 elements
Really looking forward to your answers!