#include"bits/stdc++.h"
using namespace std;
typedef long long ll;
ll dp[2005][2005];
int a[2005];
int n;
int main()
{
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		scanf("%d", &a[i]);
	}
	sort(a + 1, a + n + 1);
	cout << endl;
	for (int d = 1; d <= n - 1; d++)
	{
		for (int i = 1; i + d <= n; i++)
		{
			int j = i + d;
			dp[i][j] = a[j] - a[i] + min(dp[i + 1][j], dp[i][j - 1]);
		}
	}

	printf("%lld", dp[1][n]);
}