Given an array arr[] of size N, the task is to find the minimum sum of absolute differences of an array element with all elements of another array.
Input: arr[ ] = {1, 2, 3, 4, 5}, N = 5
Output: 3
Explanation:
For arr[0](= 1): Sum = abs(2 – 1) + abs(3 – 1) + abs(4 – 1) + abs(5 – 1) = 10.
For arr[1](= 2): Sum = abs(2 – 1) + abs(3 – 2) + abs(4 – 2) + abs(5 – 2) = 7.
For arr[2](= 3): Sum = abs(3 – 1) + abs(3 – 2) + abs(4 – 3) + abs(5 – 3) = 6 (Minimum).
For arr[3](= 4): Sum = abs(4 – 1) + abs(4 – 2) + abs(4 – 3) + abs(5 – 4) = 7.
For arr[0](= 1): Sum = 10.
Input: arr[ ] = {1, 2, 3, 4}, N = 4
Output: 2
Approach: The problem can be solved based on the observation that the sum of absolute differences of all array elements is minimum for the median of the array. Follow the steps below to solve the problem:
- Sort the array arr[].
- Print the middle element of the sorted array as the required answer.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
void minAbsDiff( int arr[], int n)
{
sort(arr, arr + n);
cout << arr[n / 2] << endl;
}
int main()
{
int n = 5;
int arr[] = { 1, 2, 3, 4, 5 };
minAbsDiff(arr, n);
return 0;
}
|
Java
import java.util.Arrays;
public class GFG
{
static void minAbsDiff( int arr[], int n)
{
Arrays.sort(arr);
System.out.println(arr[n / 2 ]);
}
public static void main(String[] args)
{
int n = 5 ;
int arr[] = { 1 , 2 , 3 , 4 , 5 };
minAbsDiff(arr, n);
}
}
|
Python3
def minAbsDiff(arr, n):
arr.sort()
print (arr[n / / 2 ])
if __name__ = = '__main__' :
n = 5
arr = [ 1 , 2 , 3 , 4 , 5 ]
minAbsDiff(arr, n)
|
C#
using System;
using System.Collections.Generic;
class GFG{
static void minAbsDiff( int []arr, int n)
{
Array.Sort(arr);
Console.WriteLine(arr[n / 2]);
}
public static void Main( string [] args)
{
int n = 5;
int []arr = { 1, 2, 3, 4, 5 };
minAbsDiff(arr, n);
}
}
|
Javascript
<script>
function minAbsDiff(arr, n){
arr.sort( function (a, b){ return a-b})
document.write(arr[(Math.floor(n / 2))])
}
let n = 5
let arr = [ 1, 2, 3, 4, 5 ]
minAbsDiff(arr, n)
</script>
|
Time Complexity: O(NlogN)
Auxiliary Space: O(1)