maximum sum of a subset of size K with sum less than M
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
This problem asks for a subset of exactly K elements whose sum is as large as possible while still staying strictly below M. A brute-force combination search works for small inputs, but if the numbers are non-negative and M is not enormous, a dynamic-programming approach is much more practical.
Brute force is the simplest baseline
The direct approach is to generate every subset of size K, compute its sum, and keep the best one that stays below M.
This is easy to understand and useful for verification, but the number of combinations grows quickly.
Dynamic programming works well for non-negative values
If the input values are non-negative integers, you can track which sums are reachable using exactly j chosen elements.
The idea is:
- '
dp[j]stores the set of sums reachable with exactlyjpicks' - start from
dp[0] = {0} - for each value, update higher
jcounts from right to left
For the example input, the best valid sum is 13.
This method is much faster than full combination search when the reachable-sum space stays manageable.
Know what assumptions the DP relies on
This style of DP is most natural when:
- values are integers
- values are non-negative
- the limit
Mis not absurdly large relative to the reachable sums
If negative values are allowed, the state space becomes more awkward. If n is small but values are huge, brute force or meet-in-the-middle may be a better fit.
So the correct algorithm depends on the shape of the input, not only on the problem statement.
Recovering the actual subset
Sometimes you need the subset itself, not only the best sum. In that case, store predecessor information instead of only reachable sums. One simple way is to map each reachable sum to the tuple that produced it.
That makes the solution more useful for real selection problems such as budgeting or packing.
Common Pitfalls
- Using a greedy choice such as "take the largest values first" even though the constraint can make that invalid or suboptimal.
- Forgetting that the subset must have exactly
Kelements, not just at mostK. - Applying the simple sum-based DP blindly when negative values are allowed.
- Treating the brute-force solution as scalable for large
n. - Returning the best sum without checking whether any valid subset of size
Kexists at all.
Summary
- Brute force is the simplest correct baseline for this problem.
- For non-negative integers, dynamic programming on subset size and reachable sums is usually much better.
- The right state is "reachable sum using exactly
jpicks." - If you need the subset itself, store predecessor or trace information.
- Always check whether the input assumptions match the algorithm you chose.

