import sys input = sys.stdin.readline N,K=map(int,input().split()) A=list(map(int,input().split())) ANS0=0 MIN=min(A) for i in range(K): ANS0+=abs(MIN-A[i]) for i in range(K,N): ANS0-=abs(MIN-A[i]) ANS1=0 MAX=max(A) A.reverse() for i in range(K): ANS1+=abs(MAX-A[i]) for i in range(K,N): ANS1-=abs(MAX-A[i]) print(min(ANS0,ANS1))