Reduce second loop to 2k-1 (where k is max_distance), when max_distance is specified