I have a set of integers M and a target sum k. I want to find the subset of M that when added together is the closest to k without going over.
For example:
Split the problem into 4 parts:
Sum containing exactly 1 element
Simply loop through and find the highest value not larger than the target.
Sum containing exactly 2 elements
Use a double for-loop to find the largest sum not larger than the target.
Sum containing exactly 3 elements (similar to 3SUM)
Sort the elements
Use a double for-loop and do a binary search for the target minus the two values, looking for smaller values to find the largest sum not larger than the target.
Sum containing exactly 4 elements
Sort the elements (already done)
Use a double for-loop to generate all sums of 2 elements.
Now, for each such sum, do a binary search on the sums for the target, looking for smaller values until we find one that doesn't contain either value which this sum is made up of.
See this for code using this approach for a similar problem (the exact sum).
Average case running time (?) = O(n + n^2 + n^2 log n + n^2 log n) = O(n^2 log n)
.
Determining the running time of the last problem is somewhat difficult, it may be as bad as O(n^4 log n)
in the worst case, as you may end up looking through most of them before you find one that fits, but this should rarely happen, and, within the same run, some should take less time, thus the overall running time may be less.