Improve algorithm logic