Optimization of minDist function