Corrected the best total cost algorithm