We need to calculate: Sigma[i] Sigma[j>i] abs(Xi-Xj) . (The indices i, j are assumed to be between 1 and k everywhere).
Since the array is sorted, Xj> = Xi for j> i. This allows you to get rid of abs , so you have:
Sigma[i] Sigma[j>i] (Xj - Xi)
This can be divided into two amounts:
Sigma[i] Sigma[j>i] Xj - Sigma[i] Sigma[j>i] Xi
For a specific j , how many times does Xj appear in the first sum? X2 appears once (only for i = 1 and j = 2), X3 appears twice (i = 1, j = 3 and i = 2, j = 3), etc. In the general case, Xj appears j-1 therefore it contributes (j-1)Xj to the amount (subject to indexing based on 1).
In the same way, Xi appears in the second sum (ki) times, so it contributes (ki)Xi to the total.
This gives the result: Sigma[j](j-1)Xj - Sigma[i](ki)Xi . This can be simplified:
Sigma[i]((2i-k-1)Xi)
This computes in O (n) instead of O (n ^ 2) for the trivial algorithm.
source share