显然直接枚举左端点(右端点)就OK啦。
#include<cstdio> #include<cstdlib> #include<algorithm> #include<cstring> #include<cmath> #define ll long long using namespace std; const int N=1e5+5; int n,a[N],ans=1e9,k; inline int Get(int x,int y){ if(x>=0) return y; if(y<=0) return -x; return y-x+min(y,-x); } int main(){ scanf("%d%d",&n,&k); for(int i=1;i<=n;i++) scanf("%d",a+i); sort(a+1,a+n+1); for(int i=k;i<=n;i++) ans=min(ans,Get(a[i-k+1],a[i])); printf("%d ",ans); return 0; }