#include <bits/stdc++.h>
#define ll long long
#define f(i, n) for (i = 0; i < n; ++i)
#define all(n) n.begin(), n.end()
#define P long(1e9 + 7)
#define fastio                        \
    ios_base::sync_with_stdio(false); \
    cin.tie(NULL)

using namespace std;

ll solve(vector<vector<ll>>& dp, vector<ll>& s, int l, int r)
{
    if (l == r)
        return dp[l][r] = 0;

    if (dp[l][r] == -1) {
        ll val = s[r] - s[l];
        val += min(solve(dp, s, l + 1, r), solve(dp, s, l, r - 1));
        return dp[l][r] = val;
    }

    return dp[l][r];
}

int main()
{
    int n, i, j, k, l, m;
    cin >> n;
    vector<ll> s(n, 0);
    vector<vector<ll>> dp(n, vector<ll>(n, -1));
    f(i, n) cin >> s[i];
    sort(all(s));

    cout << solve(dp, s, 0, n - 1);
}