#define _CRT_SECURE_NO_WARNINGS
#include<bits/stdc++.h>
#define NeedForSpeed             \
    ios_base::sync_with_stdio(0); \
    cin.tie(0);                   \
    cout.tie(0);
#define lp1(i, n) for (int i = 1; i <= n; i++)
#define lp(i, n) for (int i = 0; i < n; i++)
#define mem(n, x) memset(n, x, sizeof(n))
#define all(v) v.begin(), v.end()
#define ull unsigned long long
#define ld long double
#define pb push_back
#define ll long long
#define re return
#define sz size()
#define endl '\n'
using namespace std;
const int N = 2e3 + 5;
ll t = 1, n, m;
ll arr[N];
ll dp[N][N];
ll sol(int l,int r)
{
	if (r < l)re 0;
	ll &ret = dp[l][r];
	if (~ret)
		re ret;
	re ret = arr[r] - arr[l] + min(sol(l + 1, r), sol(l, r - 1));

}
int main()
{
	NeedForSpeed
#ifndef ONLINE_JUDGE 
		//freopen("out.out", "w", stdout);
#endif
		cin >> n; 
	mem(dp, -1);
	lp(i, n)
		cin >> arr[i];
	sort(arr, arr + n);
	cout << sol(0, n - 1) << endl;
		
		
} 

/*

*/