#![allow(unused_imports)] use std::cmp::*; use std::collections::*; use std::io::Write; use std::ops::Bound::*; #[allow(unused_macros)] macro_rules! debug { ($($e:expr),*) => { #[cfg(debug_assertions)] $({ let (e, mut err) = (stringify!($e), std::io::stderr()); writeln!(err, "{} = {:?}", e, $e).unwrap() })* }; } fn main() { let v = read_vec::(); let (n, k) = (v[0], v[1]); let mut a = read_vec::(); a.sort(); let mut b = a.iter().map(|&x| (x - a[0]).abs()).collect::>(); b.sort(); let mut ans1 = 0; for i in 0..k { ans1 += b[i]; } for i in k..n { ans1 -= b[i]; } let mut b = a .iter() .map(|&x| (a[a.len() - 1] - x).abs()) .collect::>(); b.sort(); let mut ans2 = 0; for i in 0..k { ans2 += b[i]; } for i in k..n { ans2 -= b[i]; } println!("{}", min(ans1, ans2)); } fn read() -> T { let mut s = String::new(); std::io::stdin().read_line(&mut s).ok(); s.trim().parse().ok().unwrap() } fn read_vec() -> Vec { read::() .split_whitespace() .map(|e| e.parse().ok().unwrap()) .collect() }