Mathematics Stack Exchange is a question and answer site for people studying math at any level and professionals in related fields. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have some random integers separated by space read from a text file like

99 20 30 1 100 400 5 10

I have to find a sum from any combination of these integers that is closest to a specifiq number like


what is the fastest and accurate way of doing this?

share|cite|improve this question
I guess this is similar to the subset sum problem: – PEV Jan 26 '11 at 19:26
Here is a similar question:… – PEV Jan 26 '11 at 19:28
Exact copy by same person: – Aryabhata Jan 26 '11 at 23:21

The non-trivial algorithm takes $2^{n/2}$ time and memory. Divide the list into two parts and calculate all the internal sums. Sort both lists, put one pointer at the low end of one list, and another at the high end of the other list. Advance the second pointer until the sum crosses the target. Then advance the first pointer, and repeat. Maintain the "best sum encountered so far", and once the first pointer is done traversing the list, you have the optimum in your hands.

This algorithm isn't really practical, and in practice you can probably do better, potentially depending on properties of the problem. Also, there are probably nice approximation algorithms that work well in practice.

share|cite|improve this answer

You can also have a look at

Problem 1 describes different approaches to see whether a sum K is poosible. The DP approach for the Problem 1 should give you all the numbers that are possible sum of a subset. Then you can simply do search for the nearest.

share|cite|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.