optimize the algorithm