Best combination of a sum between two parameters in an array of objects
You're right that your solution wouldn't be the most accurate. If I'm understanding your question right, what you just described is the Multi-dimensional 0-1 knapsack problem (see the &quot;Multi-dimensional knapsack problem&quot; heading in this wikipedia page). Solving these kinds of problems is not easy for computers to do quickly, and the best algorithm to use can largely depend on the type of data you're expecting to receive.
Are there very, very few items you're ever going to work with? How important is speed? Can you get away with a simple brute-force method, and try every possibility?
How much does accuracy matter? Maybe the particular use case doesn't necessarily need the best answer, just a good enough answer. If so, the code you wrote would work just fine.
Otherwise, I would read up a bit on the knapsack problem, and try googling &quot;Multi-dimensional 0-1 knapsack problem&quot; (multidimensional because you are working with multiple limits, not just weight. 0-1 because you either use the item or you don't, you can't use 1/2 an item in a package). My quick searching showed that there's a number of technical articles out there that address this exact issue. Knowing the name of the algorithm you need should help with finding more resources on it :).