const INF: isize = 1isize << 60; fn main() { let mut n = String::new(); std::io::stdin().read_line(&mut n).ok(); let n: usize = n.trim().parse().unwrap(); let mut y = String::new(); std::io::stdin().read_line(&mut y).ok(); let mut y: Vec = y.trim().split_whitespace().map(|s| s.parse().unwrap()).collect(); y.sort(); if n <= 3 { println!("{}", y[n-1] - y[0]); return; } let base = y[n-1] - y[n-2] + y[1] - y[0]; let mut dp = vec![INF; n-3]; dp[0] = base; for i in 0..dp.len()-1 { let idx = i+2; // join to left dp[i+1] = dp[i+1].min(dp[i] + y[idx] - y[idx-1]); // join to right let nidx = (i+2).min(dp.len()-1); dp[nidx] = dp[nidx].min(dp[i] + y[idx+1] - y[idx]); } println!("{}", dp[n-4]); }