#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stack>
#include <queue>
#include <vector>
#include <set>
#include <map>
#include <unordered_map>

using namespace std;

#define lowbit(x) (x & -x)
#define ls(x) (x << 1)
#define rs(x) (x << 1 | 1)

typedef long long ll;
typedef pair<int,int> PII;

const ll INF = 0x3f3f3f3f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const ll mod = 1e9 + 7;
const int N = 5e5 + 10;

int n, k;
string s;
ll f[2050][2050];
ll a[N];

ll dp(int l, int r) {
    if (l >= r) return f[l][r] = 0;
    if (f[l][r] != -1) return f[l][r];
    return f[l][r] = a[r] - a[l] + min(dp(l + 1, r), dp(l, r - 1));
}

void solve() {
    cin >> n;
    for (int i = 1; i <= n; i++) cin >> a[i];
    memset(f, -1, sizeof f);
    sort(a + 1, a + 1 + n);
    cout << dp(1, n);
}
 
int main() {   
    // freopen("make.in", "r", stdin);
    int t = 1;
    // cin >> t;
    for (int i = 1; i <= t; i++) solve();
    return 0;
}