Here is my approach O (N 2 ) . First create all possible distances;
int dist[1000000][3], ndist = 0;
for(int i = 0; i < n; i ++) {
for(int j = i + 1; j < n; j ++) {
dist[ndist][0] = abs(points[i] - points[j]);
dist[ndist][1] = i; //save the first point
dist[ndist][2] = j; //save the second point
}
}
Now sort the distances in descending order:
sort(dist, dist + ndist, cmp);
Where cmp:
bool cmp(int x[], int y[]) {
return (x[0] > y[0]);
}
Swipe through the array adding dots until you select m:
int chosen = 0;
int ans;
for(int i = 0; i < ndist; i ++) {
int whatadd = (!visited[dist[i][1]]) + (!visited[dist[i][2]);
if(chosen + whatadd > m) {
break;
}
visited[dist[i][1]] = 1;
visited[dist[i][2]] = 1;
chosen += whatadd;
ans = dist[i][0];
}
if(chosen != m) {
}
I hope this helps!