ZCO13001 - Editorial

PROBLEM SETTER -
ZCO 2013

DIFFICULTY
Easy

PREREQUISITES
Sorting

A simple brute for iterating on all the C(N,2) combinations can do the task easily for N<5000, by taking the sum of difference of all pairs of elements.

int ans=0;
for(int i = 1;i < n+1;i++)
for(int j = i+1;j < n+1;j++)


TIME COMPLEXITY -
O(N^2)

KEY OBSERVATIONS

1. Sorting the array will not cause any change to the answer as the answer does not depend on the indices of the elements.
2. Let us define a function diff(i), which denotes the sum of difference between a[i] and a[j] for all (i,j) where a[j] < a[i]. After sorting in ascending order, the above condition of a[j] < a[i] changes to j < i.

Mathematically, after sorting, diff(i) = $\sum_{j=1}^{i-1} \hspace{2mm} ( a[i] - a[j] ). \hspace{2mm}$Now,

\sum_{j=1}^{i-1} \hspace{2mm} ( a[i] - a[j] ) \hspace{2mm} = \hspace{2mm} (a[i]-a[i-1]) * (i-1) \hspace{2mm} + \hspace{2mm} \sum_{j=1}^{i-2} \hspace{2mm} ( a[i-1] -a[j ] )
\hspace{2mm} diff(i) \hspace{2mm} = \hspace{2mm} (a[i]-a[i-1]) * (i-1) \hspace{2mm} + \hspace{2mm} diff(i-1) \hspace{2mm}

The above mathematical formula clearly defines dependency of diff(i) upon diff(i-1). Consequently, the transition from i to i+1 is in O(1) time. The answer we need is summation of diff(i) for all i. Don’t forget that this observation is valid only after the array is sorted.

We first sort the array in ascending order in accordance with observation 1. We have to iterate on the sorted array and maintain 2 variables – answer and diff_i.

    sort(a+1,a+n+1);