设数组an有序,找到相邻但是未配对的a(i),与a(i+1),设a(i)与a(j)配对,a(i+1)与a(k)配对不妨设j>k,则a(j)-a(i)+a(k)-a(i+1) > a(j)-a(k) + a(i+1)-a(i)(这个不等式化简后为a(j)>a(i+1)成立),因此可以通过这样调整将相邻的数配对,因此相邻配对可以得到最小值
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int const N = 100010;
int a[N];
int main()
{
int n;
scanf("%d", &n);
for (int i = 0; i < n; i ++ ){
scanf("%d", &a[i]);
}
int res = 0;
sort(a,a+n);
for(int i=1;i<n;i++){
res += (a[i]-a[i-1]);
i++;
}
cout<<res<<endl;
return 0;
}