//#pragma comment(linker, "/STACK:102400000,102400000")
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define int ll
typedef pair<int,int>pii;
#define ff first
#define ss second
#define debug(x) std:: cerr << #x << " = " << x << std::endl;
const int maxn=2010,inf=0x3f3f3f3f,mod=1000000007;
const ll INF=0x3f3f3f3f3f3f3f3f;
const double eps=1e-9;
//#define DEBUG//#define lowbit(x) ((x) & -(x))//<<setiosflags(ios::fixed)<<setprecision(9)
void read(){}
template<typename T,typename... T2>inline void read(T &x,T2 &... oth) {
	x=0; int ch=getchar(),f=0;
	while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();}
	while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
	if(f)x=-x;
	read(oth...);
}
ll a[maxn],dp[maxn][maxn];
ll MAX[maxn][maxn],MIN[maxn][maxn];
int s[maxn][maxn];
signed main(signed argc, char const *argv[])
{
	std::ios::sync_with_stdio(false),cin.tie(0),cout.tie(0);
	#ifdef DEBUG
		freopen("input.in", "r", stdin);
	//	freopen("output.out", "w", stdout);
	#endif
	int n;
	cin>>n;
	for(int i=1;i<=n;i++)
		cin>>a[i];
	sort(a+1,a+n+1);
	memset(dp,INF,sizeof(dp));
//	memset(MIN,INF,sizeof(MIN));
	for(int i=1;i<=n;i++)
	{
		dp[i][i]=0;
//		s[i][i]=i;
//		MAX[i][i]=MIN[i][i]=a[i];
	}
	for(int len=2;len<=n;len++)
	{
		for(int l=1;l<=n-len+1;l++)
		{
			int r=l+len-1;
			dp[l][r]=min(dp[l][r-1],dp[l+1][r])+a[r]-a[l];
//			fprintf(stderr,"[%lld,%lld]=%lld\n",l,r,dp[l][r]);
//			for(int k=s[l][r-1];k<s[l+1][r];k++)
//			{
//				MAX[l][r]=max(MAX[l][k],MAX[k+1][r]);
//				MIN[l][r]=min(MIN[l][k],MIN[k+1][r]);
//				ll now=min(MAX[l][k]-MIN[k+1][r],a[r]-a[l]);
//				if(dp[l][r]>dp[l][k]+dp[k+1][r]+now)
//				{
//					dp[l][r]=dp[l][k]+dp[k+1][r]+now;
//					s[l][r]=k;
//				}
//			}
		}
	}
	cout<<dp[1][n]<<endl;
	return 0;
}
/*
 * 2021-04-16-23.54.07
*/

