
#include <bits/stdc++.h>
using namespace std;


//--------------------------------------- 
#define int         long long
#define double      long double
#define pb          push_back
#define pf          push_front
#define pii         pair<int,int>
#define vi          vector<int>
#define vii         vector<pii>
#define all(a)      (a).begin(),(a).end()
#define rall(a)     (a).rbegin(),(a).rend()
#define x           first
#define y           second
#define endl        '\n'
#define sz(x)     (int)(x).size()
#define ull       unsigned long long
//-------------------------------------------

//------------------------------------------------
#define fo(i,l,u)   for(i=l;i<u;i++)
#define rfo(i,l,u)  for(i=l;i>=u;i--)
#define allfo(s)    for(auto it=(s).begin();it!=(s).end();it++)
#define _init(b)     memset(b,-1,sizeof(b))
#define _init0(b)     memset(b,0,sizeof(b))
#define MOD         1000000007
#define hell        998244353
#define output(x) cout << (x ? "YES" : "NO")<<endl;
#define Output(x) cout << (x ? "Yes" : "No")<<endl;
//------------------------------------------------



//-----------------------------------------
#define MOD2 (998244353)
#define MOD3 (1000000009)
#define PI acos(-1)
#define eps (1e-8)
#define INF (1e18) 
 
 
 
template<class A,class B>ostream&operator<<(ostream&out,const pair<A,B>&a){return out<<"("<<a.first<<","<<a.second<<")";}
template<class A>ostream&operator<<(ostream&out,const vector<A>&a){for(const A &it:a)out<<it<<" ";return out;}
template<class A,class B>istream&operator>>(istream&in,pair<A,B>&a){return in>>a.first>>a.second;}
template<class A>istream&operator>>(istream&in,vector<A>&a){for(A &i:a)in>>i;return in;}
ifstream cinn("in.txt");ofstream coutt("out.txt");
int poww(const int &a,int b,const int &m=MOD){if(b==0)return 1;int x=poww(a,b/2,m);x=x*x%m;if(b&1)x=x*a%m;return x;} 

//---------------------------------------------------------------------------------------


int gcd(int a, int b) {if(a>b)swap(a,b) ;  if (a == 0)  return b; return gcd(b % a, a); }  
int rint(int  l , int r){return rand()%(r-l+1) + l ;}
 
//---------------------------aab code dekho bahut template dekh liya---------------------------------

const int N = 2005;
int dp[N][N];
vi v;
int f(int l, int r){
  if(l==r)return 0;
  if(dp[l][r]!=-1)return dp[l][r];
  dp[l][r] = v[r]-v[l] + min(f(l,r-1), f(l+1,r));
  return dp[l][r];
}


signed main()
{
  #ifndef ONLINE_JUDGE
   freopen("input.txt", "r", stdin);
   //freopen("output.txt", "w", stdout);
  #endif
    ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0);
// mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
   int i,j,x,n;
   cin>>n;
   fo(i,0,n){
    cin>>x;
    v.pb(x);
   }
   sort(all(v));
   _init(dp);
   cout<<f(0,n-1)<<endl;
    return 0;
}

