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

java program to find sum-of-minimum-absolute-diffrence-of-given-array_2_

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.
  • Add all the differences
  • Return the answer

Java Code finding the sum of minimum absolute difference of the given array

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;
}
}

Output
Enter the length of array
5
Enter the array elements
2
3
9
5
6
The sum of minimum absolute difference of the given array is
10