Quote:I would like to know if there is an algorithm that could help me solve the following example problem.

This problem is furiously looking like a problem from a challenge site. For this kind of problem, the solution is never simple minded or strait forward, the solution is always a unique combination algorithms.

Finding a good enough solution always needs a deep understanding of the problem.

Generally speaking, a vast knowledge of algorithm is almost mandatory.

If no idea, start with a brut force program, make it print every try it does.

Then study the prints to see if program does something stupid where it spend worthless time.

Improve code accordingly and repeat tests.

The key to success is your understanding of the problem.