Array element with minimum sum of absolute differences
Given an array arr[] of N integers, the task is to find an element x from the array such that |arr[0] - x| + |arr[1] - x| + |arr[2] - x| + ... + |arr[n - 1] - x| is minimized, then print the minimized sum.
Examples:
Input: arr[] = {1, 3, 9, 3, 6}
Output: 11
The optimal solution is to choose x = 3, which produces the sum
|1 - 3| + |3 - 3| + |9 - 3| + |3 - 3| + |6 - 3| = 2 + 0 + 6 + 0 + 3 = 11Input: arr[] = {1, 2, 3, 4}
Output: 4
A simple solution is to iterate through every element and check if it gives optimal solution or not. Time Complexity of this solution is O(n*n).
Algorithm:
Below is the implementation of the approach:
// C++ code for the approach
#include<bits/stdc++.h>
using namespace std;
// Function to find the minimum sum of absolute differences
int findMinSum(int arr[], int n) {
// Initialize the minimum sum and minimum element
int minSum = INT_MAX, minElement = -1;
// Traverse through all elements of the array
for (int i = 0; i < n; i++) {
int sum = 0;
// Calculate the sum of absolute differences
// of each element with the current element
for (int j = 0; j < n; j++) {
sum += abs(arr[i] - arr[j]);
}
// Update the minimum sum and minimum element
if (sum < minSum) {
minSum = sum;
minElement = arr[i];
}
}
// Return the minimum sum
return minSum;
}
// Driver code
int main() {
int arr[] = { 1, 3, 9, 3, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
// Find the minimum sum of absolute differences
int minSum = findMinSum(arr, n);
// Print the minimum sum
cout << minSum << endl;
return 0;
}
// C++ code for the approach
using namespace std;
// Function to find the minimum sum of absolute differences
int findMinSum(int arr[], int n) {
// Initialize the minimum sum and minimum element
int minSum = INT_MAX, minElement = -1;
// Traverse through all elements of the array
for (int i = 0; i < n; i++) {
int sum = 0;
// Calculate the sum of absolute differences
// of each element with the current element
for (int j = 0; j < n; j++) {
sum += abs(arr[i] - arr[j]);
}
// Update the minimum sum and minimum element
if (sum < minSum) {
minSum = sum;
minElement = arr[i];
}
}
// Return the minimum sum
return minSum;
}
// Driver code
int main() {
int arr[] = { 1, 3, 9, 3, 6 };
int n = sizeof(arr)/sizeof(arr[0]);
// Find the minimum sum of absolute differences
int minSum = findMinSum(arr, n);
// Print the minimum sum
cout << minSum << endl;
return 0;
}
// Java code for the approach
import java.util.*;
public class GFG {
// Function to find the minimum sum of absolute differences
public static int findMinSum(int[] arr, int n) {
// Initialize the minimum sum and minimum element
int minSum = Integer.MAX_VALUE, minElement = -1;
// Traverse through all elements of the array
for (int i = 0; i < n; i++) {
int sum = 0;
// Calculate the sum of absolute differences
// of each element with the current element
for (int j = 0; j < n; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
// Update the minimum sum and minimum element
if (sum < minSum) {
minSum = sum;
minElement = arr[i];
}
}
// Return the minimum sum
return minSum;
}
// Driver code
public static void main(String[] args) {
int[] arr = {1, 3, 9, 3, 6};
int n = arr.length;
// Find the minimum sum of absolute differences
int minSum = findMinSum(arr, n);
// Print the minimum sum
System.out.println(minSum);
}
}
# Python3 code for the approach
import sys
# Function to find the minimum sum of absolute differences
def findMinSum(arr, n):
# Initialize the minimum sum and minimum element
minSum = sys.maxsize
minElement = -1
# Traverse through all elements of the array
for i in range(n):
sum = 0
# Calculate the sum of absolute differences
# of each element with the current element
for j in range(n):
sum += abs(arr[i] - arr[j])
# Update the minimum sum and minimum element
if (sum < minSum):
minSum = sum
minElement = arr[i]
# Return the minimum sum
return minSum
# Driver code
if __name__ == '__main__':
arr = [1, 3, 9, 3, 6]
n = len(arr)
# Find the minimum sum of absolute differences
minSum = findMinSum(arr, n)
# Print the minimum sum
print(minSum)
using System;
class Program
{
// Function to find the minimum sum of absolute differences
static int FindMinSum(int[] arr, int n)
{
// Initialize the minimum sum
int minSum = int.MaxValue;
// Traverse through all elements of the array
for (int i = 0; i < n; i++)
{
int sum = 0;
// Calculate the sum of absolute differences
// of each element with the current element
for (int j = 0; j < n; j++)
{
sum += Math.Abs(arr[i] - arr[j]);
}
// Update the minimum sum
if (sum < minSum)
{
minSum = sum;
}
}
// Return the minimum sum
return minSum;
}
// Driver code
static void Main()
{
int[] arr = { 1, 3, 9, 3, 6 };
int n = arr.Length;
// Find the minimum sum of absolute differences
int minSum = FindMinSum(arr, n);
// Print the minimum sum
Console.WriteLine(minSum);
}
}
// Function to find the minimum sum of absolute differences
function findMinSum(arr) {
// Initialize the minimum sum and minimum element
let minSum = Infinity;
let minElement = -1;
// Traverse through all elements of the array
for (let i = 0; i < arr.length; i++) {
let sum = 0;
// Calculate the sum of absolute differences
// of each element with the current element
for (let j = 0; j < arr.length; j++) {
sum += Math.abs(arr[i] - arr[j]);
}
// Update the minimum sum and minimum element
if (sum < minSum) {
minSum = sum;
minElement = arr[i];
}
}
// Return the minimum sum
return minSum;
}
// Driver code
const arr = [1, 3, 9, 3, 6];
const minSum = findMinSum(arr);
// Print the minimum sum
console.log(minSum);
// This code is contributed by shivamgupta0987654321
Output
11
An Efficient Approach: is to always pick x as the median of the array. If n is even and there are two medians then both the medians are optimal choices. The time complexity for the approach is O(n * log(n)) because the array will have to be sorted in order to find the median. Calculate and print the minimized sum when x is found (median of the array).
Below is the implementation of the above approach:
// C++ implementation of the approach
#include <bits/stdc++.h>
using namespace std;
// Function to return the minimized sum
int minSum(int arr[], int n)
{
// Sort the array
sort(arr, arr + n);
// Median of the array
int x = arr[n / 2];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
int main()
{
int arr[] = { 1, 3, 9, 3, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minSum(arr, n);
return 0;
}
// C++ implementation of the approach
using namespace std;
// Function to return the minimized sum
int minSum(int arr[], int n)
{
// Sort the array
sort(arr, arr + n);
// Median of the array
int x = arr[n / 2];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
int main()
{
int arr[] = { 1, 3, 9, 3, 6 };
int n = sizeof(arr) / sizeof(arr[0]);
cout << minSum(arr, n);
return 0;
}
// Java implementation of the approach
import java.util.*;
class GFG
{
// Function to return the minimized sum
static int minSum(int arr[], int n)
{
// Sort the array
Arrays.sort(arr);
// Median of the array
int x = arr[(int)n / 2];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += Math.abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
public static void main(String args[])
{
int arr[] = { 1, 3, 9, 3, 6 };
int n = arr.length;
System.out.println(minSum(arr, n));
}
}
// This code is contribute by
// Surendra_Gangwar
# Python3 implementation of the approach
# Function to return the minimized sum
def minSum(arr, n) :
# Sort the array
arr.sort();
# Median of the array
x = arr[n // 2];
sum = 0;
# Calculate the minimized sum
for i in range(n) :
sum += abs(arr[i] - x);
# Return the required sum
return sum;
# Driver code
if __name__ == "__main__" :
arr = [ 1, 3, 9, 3, 6 ];
n = len(arr)
print(minSum(arr, n));
# This code is contributed by Ryuga
// C# implementation of the approach
using System;
class GFG
{
// Function to return the minimized sum
static int minSum(int []arr, int n)
{
// Sort the array
Array.Sort(arr);
// Median of the array
int x = arr[(int)(n / 2)];
int sum = 0;
// Calculate the minimized sum
for (int i = 0; i < n; i++)
sum += Math.Abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
static void Main()
{
int []arr = { 1, 3, 9, 3, 6 };
int n = arr.Length;
Console.WriteLine(minSum(arr, n));
}
}
// This code is contributed by mits
<script>
//Javascript implementation of the approach
// Function to return the minimized sum
function minSum(arr, n)
{
// Sort the array
arr.sort();
// Median of the array
let x = arr[(Math.floor(n / 2))];
let sum = 0;
// Calculate the minimized sum
for (let i = 0; i < n; i++)
sum += Math.abs(arr[i] - x);
// Return the required sum
return sum;
}
// Driver code
let arr = [ 1, 3, 9, 3, 6 ];
let n = arr.length;
document.write(minSum(arr, n));
// This code is contributed by Mayank Tyagi
</script>
Output
11
Time Complexity: O(n log n), where n is the size of the given array.
Auxiliary Space: O(1), no extra space is required.
We can further optimize it to work in O(n) using linear time algorithm to find k-th largest element.