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

int main() {
  ll n;
  cin >> n;

  ll a[n] ;
  for(ll i = 0; i < n ; i++) {
    cin >> a[i];
  }

  sort(a , a + n);

  vector <vector <ll>> dp(n , vector <ll> (n , 0));
  for(ll l = 1 ; l < n ; l++) {
    ll i = 0;
    while (i + l < n) {
      ll j = i + l;
      dp[i][j] = a[j] - a[i] + min(dp[i+1][j], dp[i][j-1]);
      i ++;
    }
  }

  cout << dp[0][n - 1] << endl;
  return 0;
}


