#include<bits/stdc++.h>
#define ll long long
using namespace std;

const int N = 2005;
const int mod = (int)1e9 + 7;
ll a[N],dp[N][N];
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;
    for(int i = 1;i <= n;i++){
        cin >> a[i];
    }
    sort(a + 1,a + 1 + n);
    for(int i = 0;i <= n;i++)for(int j = 0;j <= n;++j)dp[i][j] = (ll)1e18;
    for(int i = 1;i <= n;++i)dp[i][i] = 0;
    for(int l = n;l >= 1;l--){
        for(int r = l + 1;r <= n;r++){
            dp[l][r] = min(dp[l][r], dp[l][r - 1] + a[r] - a[l]);
            dp[l][r] = min(dp[l][r], dp[l + 1][r] + a[r] - a[l]);
        }
    }
    cout << dp[1][n];
    return 0;
}
