#include<iostream>
#include<algorithm>
#include<cmath>
#include<cstdio>
#include<string>
#include<cstring>
#include<queue>
#include<vector>
#include<stack>
#include<map>
#define ll long long

using namespace std;
const int INF = 0x3f3f3f3f;
const int maxn = 1e6+5;

ll n,a[maxn],vis[maxn];
ll ans = 0x3f3f3f3f3f3f3f3f;
ll dp[2005][2005];
ll dfs(int l,int r)
{
	if(dp[l][r]!=ans) return dp[l][r];
	dp[l][r] = a[r]-a[l] + min(dfs(l,r-1),dfs(l+1,r));
	return dp[l][r]; 
}

int main()
{
	cin>>n;
	for(int i = 1; i <= n; i++)
		cin>>a[i]; 
	sort(a+1,a+1+n);
	for(int i = 1; i <= n; i++)
		for(int j = 1; j <= n; j++)
			if(i == j) dp[i][j] = 0;
			else 	   dp[i][j] = ans;
	dfs(1,n);
	cout<<dp[1][n];
	return 0;
}

