Written By : MathModel
Claim #1 : Under all arrangements of the expression :
will be fixed.
Proof :
Rejecting the absolute value notation , there're two cases for each pair of integers , suppose a_i<a_j then if in an arrangement a_j appeared before a_i then we've a_j-a_i which is negative , otherwise a_i appeared before a_j then we've a_i-a_j and then a_i-a_j=-(a_j-a_i) then
thus our proof is complete.
Without Loss of Generality , we can sort the array in non-decreasing order so we've
Now we can notice a pattern :
(a_2-a_1)
(a_3-a_1)+(a_3-a_2)
(a_4-a_1)+(a_4-a_2)+(a_4-a_3)
(a_n-a_1)+(a_n-a_2)+...+(a_n-a_{n-1})
Notice that index contributes positively with i-1 copies of a_i and removes the prefix sum of from to i-1.
Let be the prefix sum of upto index which can be pre-calculated in then our expression is :
n=int(input())
a=list(map(int,input().split()))
a.sort()
p=[]
cur=0
for i in range(n):
cur+=a[i]
p.append(cur)
ans=0
for i in range(1,n):
ans+=a[i]*(i)-p[i-1]
print(ans)Complexity \mathcal{O}(n \log n).