#include<bits/stdc++.h>
#define REP(i,n) for (int i = 1; i <= n; i++)
#define mod 1000000007
#define pb push_back
#define ff first
#define ss second
#define ii pair<int,int>
#define vi vector<int>
#define vii vector<ii>
#define lli long long int
#define INF 1000000000
#define endl '\n'
const double PI = 3.141592653589793238460;
typedef std::complex<double> Complex;
typedef std::valarray<Complex> CArray;
using namespace std;

lli ar[100001];
lli dp[2001][2001];
int main()
{
	int n;
	cin>>n;
	REP(i , n) cin>>ar[i];
	
	sort(ar + 1 , ar + n + 1);
	
	REP(i , n) dp[i][i] = 0;
	
	for(int i=2;i<=n;i++)
	{
		for(int j=1;j<=n-i+1;j++)
		{
			dp[j][j+i-1] = ar[j+i-1] - ar[j] + min(dp[j+1][j+i-1] , dp[j][j+i-2]);
		}
	}
	
	cout<<dp[1][n];
	
}

