#include <bits/stdc++.h>
using namespace std;
#define rep(i,s,n) for(int i=s;i<=n;i++)
#define pb push_back
#define endl '\n'
#define ll long long int
#define pii pair<int,int>
#define pib pair<int,bool>
#define p_q priority_queue
#define inf INT_MAX-1
#define mod 1000000007
#define fir first
#define sec second
#define vi vector
#define qu queue
#define N 2000005
#define pi 3.1415926535897932384626433832795

int arr[2001];
ll dp[2001][2001];


ll solve(int st,int ed)
{
    if(st>=ed)
      return 0;
    if(dp[st][ed]!=-1)
      return dp[st][ed];
    return dp[st][ed]=arr[ed]-arr[st]+min(solve(st+1,ed),solve(st,ed-1));
    
}

void item()
{
  int n;
  cin>>n;
  rep(i,1,n)
    cin>>arr[i];
  sort(arr+1,arr+1+n);
  memset(dp,-1,sizeof(dp));
  cout<<solve(1,n)<<endl;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int t=1;
  //  cin>>t;
    while (t--)
    {
        item();
    }
    return 0;
}

