# Java Program to find sum of minimum absolute difference of the given array

## Sum of minimum absolute difference

Program to find the sum of minimum absolute difference of the array is discussed here. An array of distinct elements is given as input and the sum of minimum absolute difference of each array element has to be found.

## Example:

arr = {2, 3, 9, 5, 6}

choose optimal solution = 3

output = 12 ## Algorithm

• Sort the given array
• Find the median of the array.
• Iterate a loop through the array.
• Subtract the median from each element of the array.
• Find out the absolute value of the difference.
`import java.util.*; class Prep {     public static void main(String args[]) { 		int n;	Scanner sc = new Scanner(System.in);	System.out.println("Enter the length of array");	n=sc.nextInt();	int arr[] = new int[n];	System.out.println("Enter the array elements");	for(int i=0;i<n;i++)	{	     arr[i]=sc.nextInt();	}	System.out.println("The sum of minimum absolute difference of the given array is ");	System.out.println(absSum(arr, n)); } static int absSum(int arr[], int n) { 	Arrays.sort(arr); 	int x = arr[(int)n / 2]; 	int sum = 0; 	for (int i = 0; i < n; i++) 		sum += Math.abs(arr[i] - x); 	return sum; } }`
`OutputEnter the length of array5Enter the array elements23956The sum of minimum absolute difference of the given array is10`