#pragma GCC optimize(3)
#include <cstdio>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>
#include <cstdlib>
#include <iostream>
#include <iomanip>
#include <cmath>
#include <vector>
#include <set>
#include <map>
#include <fstream>
#include <cassert>
#include <complex>
#include <ctime>
//#include <tr1/unordered_map>
#include <bitset>
#define pii pair<int,int>
#define pdd pair<double,double>
#define pb push_back
#define fi first
#define se second
#define is insert
#define es erase
#define mkp make_pair
#define per(i,a,b) for(int i = a; i >= b; --i)
#define rep(i,a,b) for(int i = a; i <= b; ++i)

using namespace std;
//using namespace tr1;
typedef long long ll;
typedef unsigned long long ull;

inline int read()
{
    int x = 0;
    int f = 0;
    char ch = 0;
    while(!isdigit(ch))
    {
        f |= (ch == '-') ? 1 : 0;
        ch = getchar();
    }
    while(isdigit(ch))
    {
        x = (x << 3) + (x << 1) + (ch ^ 48);
        ch = getchar();
    }
    return f ? -x : x;
}

const int maxn = 2010;
int n;
int aa[maxn];
ll dp[maxn][maxn];

int main()
{
    n = read();
    int mn = 1e9,mx = 0;
    rep(i,1,n)
    {
        aa[i] = read();
    }
    sort(aa + 1,aa + n + 1);
    rep(i,0,n)
        rep(j,0,n)
            dp[i][j] = 1e18;
    rep(i,1,n)
        dp[i][i] = 0;
    rep(i,1,n)
    {
        rep(j,1,n)
            if(i + j <= n)
            {
                dp[j][i + j] = min(dp[j][i + j],dp[j][i + j - 1] + (aa[i + j] - aa[j]));
                dp[j][i + j] = min(dp[j][i + j],dp[j + 1][i + j] + (aa[i + j] - aa[j]));
            }
    }
    printf("%lld\n",dp[1][n]);
}
