#include <bits/stdc++.h>

using namespace std;

/*
n = int(input())

a = sorted(map(int, input().split()))

dp = [[-1 for r in range(n)] for l in range(n)]
for i in range(n):
    dp[i][i] = 0

for d in range(1, n):
    for l in range(n - d):
        r = l + d
        dp[l][r] = a[r] - a[l] + min(dp[l+1][r], dp[l][r-1])

print(dp[0][-1])
*/


signed main() {
    int N;
    cin>>N;
    vector<long long> v(N);
    for(int c=0;c<N;c++) cin>>v[c];
    sort(v.begin(),v.end());
    vector<vector<long long> > dp(N,vector<long long>(N,-1));

    for(int c=0;c<N;c++) dp[c][c]=0;

    for(int d=1;d<N;d++) {
        for(int l=0;l<N-d;l++) {
            int r = l + d;
            dp[l][r] = v[r]-v[l] + min(dp[l+1][r],dp[l][r-1]);
        }
    }
    cout<<dp[0].back();
}
