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

const ll mod = 1e9 + 7;

void __print(int x) {cerr << x;}
void __print(long x) {cerr << x;}
void __print(long long x) {cerr << x;}
void __print(unsigned x) {cerr << x;}
void __print(unsigned long x) {cerr << x;}
void __print(unsigned long long x) {cerr << x;}
void __print(float x) {cerr << x;}
void __print(double x) {cerr << x;}
void __print(long double x) {cerr << x;}
void __print(char x) {cerr << '\'' << x << '\'';}
void __print(const char *x) {cerr << '\"' << x << '\"';}
void __print(const string &x) {cerr << '\"' << x << '\"';}
void __print(bool x) {cerr << (x ? "true" : "false");}

template<typename T, typename V>
void __print(const pair<T, V> &x) {cerr << '{'; __print(x.first); cerr << ','; __print(x.second); cerr << '}';}
template<typename T>
void __print(const T &x) {int f = 0; cerr << '{'; for (auto &i: x) cerr << (f++ ? "," : ""), __print(i); cerr << "}";}
void _print() {cerr << "]\n";}
template <typename T, typename... V>
void _print(T t, V... v) {__print(t); if (sizeof...(v)) cerr << ", "; _print(v...);}
#ifndef ONLINE_JUDGE
#define debug(x...) cerr << "[" << #x << "] = ["; _print(x)
#else
#define debug(x...)
#endif

int run_test(){
  int n;
  cin >> n;
  vector<ll> v(n);
  for(int i = 0; i < n; i++){
    cin >> v[i];
  }
  sort(v.begin(), v.end());
  ll dp[n + 1][n + 1];
  for(int i = 0; i < n; i++){
    dp[i][i] = 0;
  }
  for(int i = n - 1; i >= 0; i--){
    for(int j = i + 1; j < n; j++){
      dp[i][j] = v[j] - v[i];
      if(i < n - 1 && j == 0){
        dp[i][j] += dp[i + 1][j];
      }
      else if(i == n - 1 && j > 0){
        dp[i][j] += dp[i][j - 1];
      }
      else{
        dp[i][j] += min(dp[i+1][j], dp[i][j-1]);
      }
    }
  }
  cout << dp[0][n - 1] << '\n';
  return 0;
}

int main()
{
  ios::sync_with_stdio(0);
  cin.tie(0); cout.tie(0);
  int tt;
  tt = 1;
  while(tt--){
    run_test();
  }
}