通过二分搜索贪心的判断条件是否成立即可。
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 100000 + 5;
const int inf = 10e9 + 10;
int stall[maxn];
bool judge(int d, int n, int c) {
int last = 0;
for (int i = 1; i < c; i++) {
int crt = last + 1;
while (crt < n && stall[crt] - stall[last] < d) {
crt++;
}
if (crt == n) {
return false;
}
last = crt;
}
return true;
}
int main(int argc, char const *argv[]) {
int n, c;
scanf("%d%d", &n, &c);
for (int i = 0; i < n; i++) {
scanf("%d", &stall[i]);
}
sort(stall, stall + n);
int left = 0;
int right = inf;
while (right - left > 1) {
int mid = (left + right) / 2;
if (judge(mid, n, c)) {
left = mid;
} else {
right = mid;
}
}
printf("%d\n", left);
return 0;
}