N,K = map(int,input().split()) A = sorted(list(map(int,input().split()))) ans = sum(A) if K==1: ans = A[N-1]-A[0] elif K==2: for i in range(1,N): cnt = A[i-1]-A[0]+A[N-1]-A[i] ans = min(ans,cnt) else: for i in range(1,N-K+2): cnt = A[i-1]-A[0]+A[N-1]-A[i+K-2] ans = min(ans,cnt) print(ans)