from collections import * from itertools import * from functools import * from heapq import * import sys,math input = sys.stdin.readline N = int(input()) A = list(map(int,input().split())) A.sort() S = list(accumulate([0]+A)) ans = 0 for i in range(1,N-1): m = A[i] l = min(i-0,N-i-1) if (A[i-l] + A[N-l]) >= 2*m: val = S[i] - S[i-l] + S[-1] - S[-1-l] - 2*l*m ans = max(ans,val) continue elif A[i-1]+A[N-1] < 2*m: continue else: y = l x = 1 while y - x > 1: mid = (y+x)//2 if (A[i-mid] + A[N-mid]) >= 2*m: x = mid else: y = mid val = S[i] - S[i - x] + S[-1] - S[-1-x] - 2*x*m ans = max(ans,val) print(ans)