#include <bits/stdc++.h>
using namespace std;
#define int int64_t
//#define uint uint64_t
#define F first
#define S second
#define pii pair<int,int>
#define ld long double

int32_t main()
{
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int n;
    cin >> n;
    int a[n];
    for (int i=0;i<n;++i) {
        cin >> a[i];
    }
    sort(a, a+n);
    int dp[n][n];
    for (int i=0;i<n;++i) {
        for (int j=0;j<n;++j) {
            dp[i][j] = 1e17;
        }
        dp[i][i] = 0;
    }
    for (int sz=1;sz<n;++sz) {
        for (int i=0;i+sz<n;++i) {
            dp[i][i+sz] = min(dp[i+1][i+sz], dp[i][i+sz-1]) + a[i+sz] - a[i];
        }
    }
    cout << dp[0][n-1];
    return 0;
}

