#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define int long long
#define inf 1000000000000000000 
int mod=1e9+7;
int min(int a,int b){return (a<b)?a:b;}
int max(int a,int b){return (a>b)?a:b;}
int fp(int a,int b){if(b==0) return 1;int x=fp(a,b/2);x=(x*x)%mod;if(b&1) x=(x*a)%mod;return x;}
auto random_add = [] { char *p = new char; delete p; return uint64_t(p); };
const uint64_t SEED = chrono::steady_clock::now().time_since_epoch().count() * (random_add() | 1);
mt19937_64 rng(SEED);
 
 
const int N=2e3+5;
 vector<int> a;
 int dp[N][N];
int solve(int l,int r)
{
    if(l==r)
        return 0;
    if(dp[l][r]!=-1)
        return dp[l][r];
    return dp[l][r]=min(a[r]-a[l]+solve(l+1,r),a[r]-a[l]+solve(l,r-1));
}
 
void solve()
{
    int n;
    cin>>n;
    memset(dp,-1,sizeof(dp));
    a=vector<int>(n);
    for(int i=0;i<n;i++){
        cin>>a[i];
    }
    sort(a.begin(),a.end());
    cout<<solve(0,n-1)<<endl;
}
 
signed main() {
 ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); 
 srand(time(0));
 int t=1;
 //cin>>t;
 for(int i=1;i<=t;i++){
   solve();
 }
}