Improve algorithm (GOOD VERSION)