n,k = map(int,input().split()) a = list(map(int,input().split())) k = n-k ans = 10**15 b = [1]*(n-k)+[-1]*k ruiseki = [0]*(n+1) for i in range(n): ruiseki[i+1] = ruiseki[i]+b[i] base = 0 before_base = -1 while base+1 < n and ruiseki[base+1] < (n-2*k+1)//2: before_base = base while base+1 < n and a[base] == a[before_base]: base += 1 left = sum(abs(a[i]-a[base]) for i in range(n-k))+sum(-abs(a[base]-a[i]) for i in range(n-k,n)) ans = min(ans,left) if before_base != -1: left = sum(abs(a[i]-a[before_base]) for i in range(n-k))+sum(-abs(a[before_base]-a[i]) for i in range(n-k,n)) ans = min(ans,left) b = [-1]*k+[1]*(n-k) ruiseki = [0]*(n+1) for i in range(n): ruiseki[i+1] = ruiseki[i]+b[i] base = n-1 before_base = -1 while 0 < base and ruiseki[n]-ruiseki[base] < (n-2*k+1)//2: before_base = base while 0 < base and a[base] == a[before_base]: base -= 1 right = sum(-abs(a[i]-a[base]) for i in range(k))+sum(abs(a[base]-a[i]) for i in range(k,n)) ans = min(ans,right) if before_base != -1: right = sum(-abs(a[i]-a[before_base]) for i in range(k))+sum(abs(a[before_base]-a[i]) for i in range(k,n)) ans = min(ans,right) ans = min(ans,left,right) print(ans)