Sum of differences#12231

Sum of differences (Editorial)

Written By : MathModel

Claim #1 : Under all arrangements of the expression :

\sum_{i=1}^n \sum_{j=i+1} |a_i-a_j|

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

|a_i-a_j|=|a_j-a_i|

thus our proof is complete.

Without Loss of Generality , we can sort the array in non-decreasing order so we've

a_1 \le a_2 \le a_3 \le ... \le a_n

Now we can notice a pattern :

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 :

\sum_{i=2}^n a_i \times (i-1) + p[i-1]
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).