So, unfortunately, there is no efficient algorithm out there which will give you the optimal solution. (If you happen to write one, you win $1,000,000 http://www.claymath.org/mi

So, that said, your options are:

1. Write an algorithm to try most of the possible combinations.

2. Write an algorithm that will run faster, but won't guarantee the best.