Fix the algorithm logic