#include<bits/stdc++.h>
// #pragma GCC target ("avx2")
// #pragma GCC optimization ("O3")
// #pragma GCC optimization ("unroll-loops")
typedef long long ll;
using namespace std;
#define V vector<ll>
#define VV vector<vector<ll>>
#define A(a) for(auto &x:a)cin>>x;
#define C(a) cout<<(#a);for(auto x:a)cout<<" "<<x;cout<<endl;
#define D(a) cout<<(#a)<<"-> "<<a<<endl;
#define DD(a,b) cout<<(#a)<<"-> "<<a<<" "<<(#b)<<"-> "<<b<<endl;
#define Q int tt,qq; cin>>tt ;for(qq=1;qq<=tt;qq++)
#define I ios::sync_with_stdio(false); cin.tie(0); cout.tie(0);
#define B(a) a.begin(),a.end()
#define yes cout<<"YES"<<endl;
#define no cout<<"NO\n";
ll M=1000000007,inf=9223372036854775807;
#define N 200010
ll dp[2005][2005],a[2005];
ll call(int l,int r){
	if(l==r)return 0;
	if(dp[l][r]!=-1)return dp[l][r];
	dp[l][r]=a[r]-a[l]+min(call(l+1,r),call(l,r-1));
	return dp[l][r];
}
int main()
{
	memset(dp,-1,sizeof(dp));
	ll n,i;
	cin>>n;
	for(i=0;i<n;i++){
		cin>>a[i];
	}
	sort(a,a+n);
	cout<<call(0,n-1)<<endl;;
}