// Muallif: Azimjon Mehmonali o'g'li
 
#include <bits/stdc++.h>
 
using namespace std;
 
#define int long long

const long double PI = 3.1415926535897;
const int mod = 1000000007LL;
const int INF = 1e18;

void f(){
    int n;
    cin >> n;

    vector<int> a(n);
    if (n == 1) {
        cout << 0 << endl;
        return;
    }

    for (int &i : a) {
        cin >> i;
    }
    

    sort(a.begin(), a.end());
  
    vector<vector<int>> d(n, vector<int>(n, INF));

    function<int(int, int)> dfs = [&](int l, int r) {
        if (l == r) return 0ll;

        if (d[l][r] != INF) return d[l][r];

        int x = a[r] - a[l] + min(dfs(l + 1, r), dfs(l, r - 1));

        return (d[l][r] = x);
    };

    cout << dfs(0, n - 1) << endl;
}

signed main() {
	//
    ios::sync_with_stdio(0);
	cin.tie(0);
    //

    int t = 1;
    // cin >> t;

    while (t--)
        f();
    
	return 0;
}