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/millennium/ so don't try unless you have a few years of free time and an I.Q. > 150 because that offer's been out there quite some time)

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.