/*
start of cp 3.0BETA
NEW-BETA-LADDER
https://codeforces.com/problemset/page/1?tags=1800-1800
DEAD PERSON CODING
*/
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define MOD 1000000007
#define int long long int
#define pii pair<int,int>
#define vi vector<int>
#define vii vector<pii>
#define graph vector<vector<int>>
#define print(s) for(auto it:s) cout<<it<<" "
#define print2(s) for(auto it:s) cout<<it.fi<<" : "<<it.se
#define uset unordered_set
#define maxheap priority_queue<int>
#define minheap priority_queue<int,vi,greater<int>>
#define ln cout<<'\n'
#define space cout<<" "
#define len(x) x.size()
#define bits(x) _builtin_popcount(x)
void fileio()
{
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    #endif
}
graph g;
const int N=2001;
int dp[N][N],n;
vi a;
int solve(int l,int r){
    if(l>=r)return 0;
    int &res=dp[l][r];
    if(res!=-1)return res;
    res=1e18;
    res=a[r]-a[l]+min(solve(l+1,r),solve(l,r-1));
    return res;
}
int32_t main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    fileio();
    cin>>n;
    a=vi(n,0);
    for(int i=0;i<n;i++)cin>>a[i];
    memset(dp,-1,sizeof(dp));
    sort(a.begin(), a.end());
    cout<<solve(0,n-1);
    return 0;
}

        