
Suppose the given array is [ 2, 5, 8, 9 ]. So you have to return [ 16, 10, 10, 12 ] as the output as :
‘16’ = | 2 - 2 | + | 2 - 5 | + | 2 - 8 | + | 2 - 9 | = 0 + 3 + 6 + 7
‘10’ = | 5 - 2 | + | 5 - 5 | + | 5 - 8 | + | 5 - 9 | = 3 +0 + 3 + 4
‘10’ = | 8 - 2 | + | 8 - 5 | + | 8 - 8 | + | 8 - 9 | = 6 + 3 + 0 + 1
‘12’ = | 9 - 2 | + | 9 - 8 | + | 5 - 9 | + | 12 - 12 | = 7 + 1 + 4 + 0
The first line of input contains a ‘T’ number of test cases. Then next ‘T’ follows.
The first line of each test case contains an integer ‘N’ i.e size of the array ‘POS’.
The second line of each test case contains an array ‘POS’, where ‘POS[i]’ denotes the value for the ‘ith’ index.
For each test case, return an array containing the sum of the absolute difference of each element with each element.
You don't need to print anything; it has already been taken care of. Just implement the given function.
1 <= T <= 10^2
1 <= N <= 10^3
1 <= POS[i] <= 10^4
Time Limit: 1 sec
The idea here is to use a brute approach. For each and every element, we find the absolute value and then take the sum and stored it in an array.
Suppose we have to find the answer of ‘i-th’ house then:
‘ANS[i] = ∑ abs(POS[i] - POS[j]), for every ‘j’ from ‘0’ to ‘n-1’.
The idea here is to find the total sum of the array/list and using the property of a sorted array that left side elements are smaller and larger elements lie on the right side. So, we can use this formula ( no of elements on the left side * current element - no of elements on the right side * current element ).