#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[2010];
ll b[2010];
ll c[2010][2010];
ll d[2010][2010];
void solve(){
    int n;
    cin >> n;
    if(n == 1){cin >> a[1];cout << 0 << '\n';}
    else{
    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++){
            c[i][j]=a[j]-a[i];
        }
    }
    for(int i = 1; i < n; i++)
    {
        for(int j = n; j > i; j--)
        {
            if(i == 1&&j == n)d[i][j] = c[i][j];
            else if(i == 1)d[i][j] = c[i][j] + d[i][j + 1];
            else if(j == n)d[i][j] = c[i][j] + d[i - 1][j];
            else d[i][j] = c[i][j] + min(d[i][j + 1],d[i - 1][j]);
        }
    }
    ll ans = d[1][2];
    for(int i = 1; i < n; i++)
    {
        ans = min(ans,d[i][i+1]);
    }
    ll sum=0;
    
    cout<<ans<<'\n';
    }
}
int main(){
    solve();
}