Finds the optimal solution