How do you find the maximum sum <= K in an array with no other constraints (elements don't have to be contiguous or non-contiguous)
2 Answers
This can be solved using the dynamic programming algorithm for the 0/1 knapsack problem with element values set equal to element weights.
Comments
This is a variation of the subset sum problem.
This problem is NP-Complete, so there is no known polynomial solution.
However, if your list contains relatively small integers, there is an efficient Dynamic Programming pseudo-polynomial solution.
Other alternative is checking all 2^n possible subsets and checking the best out of them.