Improve algorithm