Minimizing the cost function