Absolute distance from various points in O(n)

Viewed 297

I am stuck in question. The part of the question requires to calculate sum of absolute distance of a point from various points. |x - x1| + |x - x2| + |x - x3| + |x - x4| ....

I have to calculate this distance in O(n) for every point while iterating in array for eg:

array = { 3,5,4,7,5}
sum of distance from previous points

dis[0] = 0;
dis[1] = |3-5| = 2
dis[2] = |3-4| + |5-4| = 2
dis[3] = |3-7| + |5-7| + |4-7| = 9
dis[4] = |3-5| + |5-5| + |4-5| + |7-5| = 5

Can anyone suggest the algo to do this ? Algorithm for less than O(n^2) will be appreciated ( not necessarily O(n)).

Code for O(n^2)

REP(i,n){
   LL ans = 0;
   for(int j=0;j<i;j++)
      ans= ans + abs(a[i]-a[j])
   dis[i]=ans;
}
2 Answers
Related