











Finding sum of minimum absolute difference of array using Python
Sum of minimum absolute difference of array
To find minimum absolute difference of array we will take median of the given array and find out the absolute difference between median and each element of array and add all together
Finding median
we can find median by two methods
1) sort the array in ascending order , and find the middle element . If array length is even median becomes average of array[length/2 -1] and array[length/2] .If array length is odd median will be array[length/2]
2) Using statistics module
Check the image how to find median using first method
- Example 1: Array 11,3,2,4,1 Median-3
- sum=|11-3|+|3-3|+|2-3|+|4-3|+|1-3|
- sum of absolute difference of array=12


Algorithm 1:
- Read input array
- Sort array in ascending order to find median
- According to length of array median of array changes
- Subtract the median from each element of the array
- Add all the differences
- Display the sum
Python code:
a=list(map(int,input(“Enter array “).split()))
a.sort()
n=len(a)
if(n%2==1):
me=a[n//2]
else:
me=(a[n//2 –1]+a[n//2] )/2
z=0
for i in a:
z+=abs(i-me)
print(“Sum of minimum absolute difference of array is”,end=” “)
print(z)
Output:
Enter array 2 3 9 5 6
Sum of minimum absolute difference of array is 10
Algorithm 2:
- Input an array and find the median of the array.
2. Iterate a loop through the array.
3. Subtract the median from each element of the array.
4. Find out the absolute value of the difference.
5. Add all the differences
6. Display the sum
Python Code:
import statistics
#Syntax for reading space seperated integers
a=list(map(int,input(“Enter array”).split()))
#statistics module has method for finding median
me=statistics.median(a)
z=0
for i in a:
z+=abs(a-me)
print(“Sum of minimum absolute difference of array is”,end=“”)
print(z)
Output:
Enter array 2 3 9 5 6
Sum of minimum absolute difference of array is 10
Login/Signup to comment