Optimize distance algorithm