If your question is “give the code,” I’m afraid that you did not give enough information to implement a good solution. If you read this whole answer, you will understand why.
If your question is "gimme the algorithm", I'm afraid you are looking for the answer in the wrong place. This is a technology-oriented site, not an algorithm-oriented one. Despite the fact that we programmers, of course, understand the algorithms (for example, why it is inefficient to pass the same line to strlen at each iteration of the loop, or why the sorting of bubbles is not OK, except for very short lists), most of the questions here for example, "how to use API X using language / framework Y?".
Answers to complex algorithms such as this one require some experience (including, but not limited to, a lot of mathematical skills). People in the field of operations research have worked more in these problems than most of us have ever had. Here is an introductory book on the topic.
As an engineer trying to find a practical solution to a real problem, I would first get the answers to these questions:
How big is the average problem you are trying to solve? . Since your general problem is NP-complete (as Jitamaro already said), moderately large problems require the use of heuristics. If you are only going to solve problems with small problems, you may be able to avoid an algorithm that will find the exact optimum, but, of course, you should You will warn your users that they should not use your software to solve large problem situations.
Are there any patterns you could use to reduce the complexity of the problem? . For example, do elements always or almost always appear in certain sizes or quantities? If so, you can implement a greedy algorithm that focuses on providing high-quality solutions for common scenarios.
What would be your optimality or compromise between computing efficiency? If you need only a good answer, you should not spend mental or computational efforts to provide an optimal answer. Information provided by a personal computer is useful only when it is available, when it is needed.
How much are your customers willing to pay for a high-quality solution? Unlike a database or web programming, which can be performed by almost everyone, since the algorithms are minimized (for example, you rarely specify the exact procedure by which the SQL database provides the result of a query), operations research requires both mathematical and engineering skills. If you do not charge for them, you lose money.
source share