N = int(input()) Y = list(map(int, input().split())) Y.sort() if N <= 3: print(Y[-1] - Y[0]) exit() INF = float('inf') dp = [0] * (N + 1) dp[0] = INF dp[1] = 0 dp[2] = Y[1] - Y[0] dp[3] = Y[2] - Y[0] for i, y in enumerate(Y[3:], start=3): d2 = dp[i - 2] + y - Y[i - 2] # xxx o o d3 = dp[i - 3] + y - Y[i - 1] + Y[i - 2] - Y[i - 3] # xxx o o o dp[i + 1] = min(d2, d3) print(dp[-1])