2 0
 6 8
1 4 1
1 5 1
1 6 1
2 4 1
2 5 1
2 6 1
3 5 1
3 6 1
 6 12
1 3 8763000
1 4 8763000
1 5 8763000
1 6 8763000
2 3 8763000
2 4 1
2 5 8763000
2 6 1
3 5 8763000
3 6 8763000
4 5 8763000
4 6 2

0
 0
 8763002

#include <bits/stdc++.h>
using namespace std;
long ans = 0;
int a[20001];
int n;
vector<vector<long long>> dp;
long long solve(int up, int down) {
  if (up == down) return dp[up][down] = 0;
  if (a[up] == a[down]) return dp[up][down] = 0;
  if (dp[up][down] != -1) return dp[up][down];
  return dp[up][down] =
             (min(solve(up - 1, down), solve(up, down + 1)) + a[up] - a[down]);
}
int main() {
  int up, down;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i];
  }
  for (int i = 0; i < n; i++) {
    dp.push_back(vector<long long>());
    for (int j = 0; j < n; j++) {
      dp[i].push_back(-1ll);
    }
  }
  sort(a, a + n);
  cout << solve(n - 1, 0);
}
