#define _CRT_SECURE_NO_WARNINGS 
using namespace std;
#include<bits/stdc++.h>

#define fast ios_base::sync_with_stdio(false),cin.tie(0),cout.tie(0)
#define vi vector<int>
#define lp(i , n) for(int (i)=0 ; i<(n) ; i++)
#define lp1(i , n) for(int (i)=1 ; i<=(n) ; i++)
#define loop(i, a, b) for(int i = a; i <= b; i++)
#define all(v) (v).begin() , (v).end() 
#define si set<int >
#define vc vector<char>
#define ll long long
#define vs vector<string>
#define vll vector<ll>
#define vvi vector<vi>		
#define vvl vector<vll>		
#define vvc vector<vc>		
#define pii pair<int ,int >
int dx[4] = { 0 , 0 , 1 , -1 };	// x ,y+1    x+1,y   x , y-1    x-1 , y    
int dy[4] = { 1 , -1 , 0 , 0 };
//int dx[8] = { 0 , 0 , 1 , -1 , 1 , -1 , -1 , 1};	// x ,y+1    x+1,y   x , y-1    x-1 , y    
//int dy[8] = { 1 , -1 , 0 , 0 , -1 , -1 ,  1 , 1};

//************************************************** SHARK ************* ******************************//
const int N = 2e3 + 2;
int n; 
ll arr[N]; 
ll mem[N][N];
ll solve(int i, int x) {
	if (i > x) return 0;
	ll &ret = mem[i][x]; 
	if (ret != -1)  return ret; 
	return ret = abs(arr[i] - arr[x]) + min(solve(i + 1, x), solve(i, x - 1));
}

int main() {
	fast;
	cin >> n;
	lp(i, n) cin >> arr[i];
	sort(arr, arr + n);
	memset(mem, -1, sizeof mem); 
	cout << solve(0, n - 1); 
}
