#include<bits/stdc++.h>
using namespace std;
#define ll long long
#define mod (ll)1e9+7;
#define test ll t;cin>>t;while(t--)
#define endl "\n"
#define pb push_back
#define vi vector<int>
#define vvi vector<vi>
#define vl vector<ll>
#define vvl vector<vl>
#define vp vector<pair<int,int>>
#define pf push_front
#define fast ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL);
#define scanint(x) int x;cin>>x;
#define scanll(x) ll x;cin>>x;
#define scanstr(str) string str;cin>>str;
#define scanchr(chr) char chr;cin>>chr;
#define all(c) (c).begin(), (c).end()
#define vecread(vec) for(auto &x:vec){cin>>x;}
#define calcTime cerr << "time taken : " << (float)clock() / CLOCKS_PER_SEC << " secs" << endl
#define debug(a) cout<<a<<endl;
#define debug2(a,b) cout<<a<<" "<<b<<endl;
#define debug3(a,b,c) cout<<a<<" "<<b<<" "<<c<<endl;
#define joker(V) for(auto X:V)cout<<X<<" ";cout<<endl;
#define papiya(Mp) for(auto X:Mp)cout<<X.first<<" "<<X.second<<endl;


void solve(){
    scanint(n)
    vi arr(n);
    vecread(arr);

    sort(all(arr));

    vvl dp(n, vl(n));

    for (size_t g = 0; g < n; g++)
    {
        for(int i = 0, j = g; j < n; i++, j++){
            if(g == 0){
                dp[i][j] = 0;
            } else if(g == 1){
                dp[i][j] = abs(arr[i] - arr[j]);
            } else {
                dp[i][j] = arr[j] - arr[i] + min(dp[i + 1][j], dp[i][j - 1]);
            }
        }
    }
    
    cout << dp[0][n - 1] << endl;
}

int main()
{
    fast
    #ifndef ONLINE_JUDGE
    freopen("input.txt", "r", stdin);
    #endif

    // test
    // {
        solve();
    // }

    calcTime;
    return 0;
}