Given a listof N integers, your task isto select K integers fromthelist such thatits unfairness is minimized.
if (x1,x2,x3,…,xk) are K numbers selected fromthelist N, the unfairness is defined as
max(x1,x2,…,xk)−min(x1,x2,…,xk)
where max denotes the largest integer among the elements of K, and min denotes the smallest integer among the elements of K.
答案
#include <cmath>#include <cstdio>#include <vector>#include <iostream>#include <algorithm>#include <climits>usingnamespacestd;
int main() {
int N, K, unfairness = INT_MAX;
cin >> N >> K;
intlist[N];
for (int i=0; i<N; i++)
cin >> list[i];
vector<int> dat(list,list+sizeof(list)/sizeof(list[0]));
sort(dat.begin(),dat.end());
int j=K-1;
int ret=numeric_limits<int>::max();
while(j<N){
ret=min(ret,dat[j]-dat[j-K+1]);
j++;
}
//cout<<ret<<endl;/** Write the solution code here. Compute the result, store in the variable unfairness --
and output it**/
unfairness=ret;
cout << unfairness << "\n";
return0;
}