二分搜答案。
做最大最小值,最小最大值,最大平均值,最小平均值都可以先设定一个值,然后去看符不符合题意,用二分搜索可以完全。
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<cstdlib>
#include<climits>
#include<stack>
#include<vector>
#include<queue>
#include<set>
#include<map>
#define up(i,a,b) for(int i=a;i<b;i++)
#define dw(i,a,b) for(int i=a;i>b;i--)
#define upd(i,a,b) for(int i=a;i<=b;i++)
#define dwd(i,a,b) for(int i=a;i>=b;i--)
//#define local
typedef long long ll;
const double esp = 1e-6;
const double pi = acos(-1.0);
const long long INF = 0x3f3f3f3f;
using namespace std;
typedef pair<int, int> pir;
int n, c;
int a[1000005];
bool judge(int len)
{
//cout <<"len "<< len;
int num = 0;
up(i, 1, c)
{
int cnt = num + 1;
while (cnt < n&&a[cnt] - a[num] < len)
cnt++;
if (cnt == n)return false;
num = cnt;
}
return true;
}
int main()
{
cin >> n >> c;
up(i, 0, n)
{
scanf("%d", &a[i]);
}
sort(a, a + n);
int lf = 1;
int rt =a[n-1]-a[0];
int mid = 0;
while (lf<=rt)
{
mid = (lf + rt) >> 1;
if (judge(mid))lf = mid+1;
else rt = mid-1 ;
}
cout << rt;
return 0;
}