Given a sorted array of N elements, I need to find the absolute sum of the differences of all elements.
Given 4 elements (1, 2, 3 and 4):
|1-2|+|1-3|+|1-4|+|2-3|+|2-4|+|3-4| = 10
Here is my code in Java:
List<Integer> a = new ArrayList<Integer>(); //just for understanding , the Array List is already filled with numbers
public static int lsum(int N)
{
int sum =0;
for( int i=0;i<N;i++)
{
int w =a.get(i);
for(int j =i;j<N;j++)
{
int z = a.get(j);
sum =sum +(z-w);
}
}
return(sum);
}
I'm looking for an efficient algorithm rather than the trivial one I am using (O(n2) complexity). This is a requirement for a bigger program which requires this function. The input (number of elements) can be as big as 105.
min
? 2. Don't you needabs
somewhere? 3. Do we know anything about the numbers in the array (i.e., their span, distribution,...)? 4. Settingj=i+1
instead ofj=i
will save youN
steps. \$\endgroup\$