#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <string>
#include <vector>
#include <unordered_map>
#include <map>
#include <set>
#include <unordered_set>
#include <queue>
#include <algorithm>

//#define TEST 1
#define Maxn 1000000007
typedef long long ll;

using namespace std;

#define N 2002

long long f[N][N];
long long arr[N];

long long dp(int x, int y)
{
    if (f[x][y]>=0) return f[x][y];
    if (x==y) return f[x][y] = 0;
    long long res1 = dp(x+1, y) + arr[y] - arr[x];
    long long res2 = dp(x, y-1) + arr[y] - arr[x];
    return f[x][y] = std::min(res1, res2);
}

int main()
{
    int n;
    scanf("%d", &n);
    for (int i=0; i<n; i++) scanf("%lld", &arr[i]);
    sort(arr, arr+n);
    memset(f, -1, sizeof(f));
    long long ans = dp(0, n-1);
    printf("%lld\n", ans);

    return 0;
}