/******************************************************************************

                              Online C++ Compiler.
               Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.

*******************************************************************************/

#include <bits/stdc++.h>

using namespace std;

using ll=long long; 

int main()
{
    ll n,i,j,k;
    cin>>n;
    ll arr[n],dp[n][n];
    for(i=0;i<n;i++)
    {
        cin>>arr[i];
    }
    sort(arr,arr+n);
    for(i=0;i<n;i++)
    {
        for(j=0;j<n;j++)
        {
            dp[i][j]=(ll)1e18;
        }
    }
    for(i=0;i<n;i++)
    {
        for(j=0;j+i<n;j++)
        {
            if(i==0)
            {
                dp[j][j+i]=0;
            }
            else{dp[j][j+i]=min(dp[j][j+i-1]+arr[j+i]-arr[j],((j+1<n)?dp[j+1][j+i]+arr[j+i]-arr[j]:(ll)1e18));}
            //cout<<dp[j][j+i]<<" "<<arr[j]<<" "<<arr[j+i]<<" "<<"\n";
        }
    }
    cout<<dp[0][n-1];

    return 0;
}
