I have some random integers like
99 20 30 1 100 400 5 10
I have to find a sum from any combination of these integers that is closest(equal or more but not less) to a given number like
183
what is the fastest and accurate way of doing this?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
If your numbers are small, you can use a simple Dynamic Programming(DP) technique. Don’t let this name scare you. The technique is fairly understandable. Basically you break the larger problem into subproblems.
Here we define the problem to be
can[number]. If thenumbercan be constructed from the integers in your file, thencan[number]istrue, otherwise it isfalse. It is obvious that0is constructable by not using any numbers at all, socan[0]istrue. Now you try to use every number from the input file. We try to see if the sumjis achievable. If analready achieved sum + current number we try == j, thenjis clearly achievable. If you want to keep track of what numbers made a particular sum, use an additionalprevarray, which stores the last used number to make the sum. See the code below for an implementation of this idea: