/*
Created by : Ivan Deka
About me : Just a coder trying to code out the best of me!
*/
#include<bits/stdc++.h>
using namespace std;

typedef int long long ll;
typedef unsigned int long long ul;
typedef long double ld;

#define mod 1000000007
#define mod1 998244353
#define pb push_back
#define mk make_pair
#define vi vector<ll>
#define pii pair<ll, ll>
#define ff first
#define ss second
#define all(v) v.begin(), v.end()
#define sz(a) a.size()
#define ub(a,x) upper_bound(all(a),x) - a.begin()
#define lb(a,x) lower_bound(all(a),x) - a.begin()

ll inline powerM(ll a, ll b, ll p){
    a %= p;
    ll ans = 1;
    while(b>0){
        if(b & 1)
            ans = (ans*a)%p;
        a = (a*a)%p;
        b >>= 1;
    }
    return ans;
}

ll inv(ll n, ll p){
    return powerM(n,p-2, p);
}

ll inline power(ll a, ll b){
    //a %= p;
    ll ans = 1;
    while(b>0){
        if(b & 1)
            ans = (ans*a);
        a = (a*a);
        b >>= 1;
    }
    return ans;
}

ll n;
ll a[3000];
ll dp[3000][3000];
ll fun(ll i,ll j)
{
    if(i==j) return 0;
    if(dp[i][j]!=-1) return dp[i][j];
    dp[i][j]=a[j]-a[i]+min(fun(i+1,j),fun(i,j-1));
    return dp[i][j];
}
void solve()
{
    cin>>n;
    for(ll i=0;i<n;i++)
    {
        cin>>a[i];
    }
    memset(dp,-1,sizeof(dp));
    sort(a,a+n);
    cout<<fun(0,n-1)<<"\n";
}

int main()
{
    //ϳᕱᎥ ♅ᕱภuოᕱภ
    ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);

    ll t=1;
    //cin>>t;
    for(ll i=1;i<=t;i++)
    {
        //cout<<"Case #"<<i<<":"<<" ";
        solve();
    }
}