Minimum sum of differences with an element in an array
Last Updated :
29 Nov, 2023
Given an array, we need to find the sum of elements of an array after changing the element as arr[i] will become abs(arr[i]-x) where x is an array element.
Examples:
Input : {2, 5, 1, 7, 4}
Output : 9
We get minimum sum when we choose
x = 4. The minimum sum is
abs(2-4) + abs(5-4) + abs(1-4) + (7-4)
abs(4-4) = 9
Input : {5, 11, 14, 10, 17, 15}
Output : 20
We can either choose x = 14 or x = 11
Naive Approach:
The naive approach to solve the problem can be like: We pick each element of the array and then traverse entire array to store sum of absolute difference of the picked element and ith element. After traversal of the array, we keep updating a variable say res with minimum of the current sum that we get after traversal and the previous value that variable res will be having. Finally, after going through each element of the array the same way we will be having our answer in res variable.
Algorithm:
- Define a function “findSum” which takes an integer array “arr”, its size “n” and an integer “x” as input.
- Initialize a variable “res” to a very large number.
- For each element “i” in the array “arr”, do the following:
a. Initialize a variable “sum” to 0.
b. For each element “j” in the array “arr”, do the following:
i. Calculate the absolute difference between the elements “arr[i]” and “arr[j]”. This can be done by subtracting “arr[j]” from “arr[i]” and taking the absolute value of the result using the “abs()” function.
ii. Add this absolute difference to the variable “sum”.
c. If the value of “sum” is less than the current value of “res”, update the value of “res” to “sum”.
4. Return the value of “res”.
Below is the implementation of the approach:
C++
#include <bits/stdc++.h>
using namespace std;
int calculateSum( int arr[], int n, int x) {
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += abs (arr[i] - x);
}
return sum;
}
int findMinSum( int arr[], int n) {
int res = INT_MAX;
for ( int i = 0; i < n; i++) {
int sum = calculateSum(arr, n, arr[i]);
res = min(res, sum);
}
return res;
}
int main() {
int arr[] = { 5, 11, 14, 10, 17, 15 };
int n = sizeof (arr) / sizeof (arr[0]);
int minSum = findMinSum(arr, n);
cout << minSum << endl;
return 0;
}
|
Java
public class Main {
static int calculateSum( int [] arr, int n, int x) {
int sum = 0 ;
for ( int i = 0 ; i < n; i++) {
sum += Math.abs(arr[i] - x);
}
return sum;
}
static int findMinSum( int [] arr, int n) {
int res = Integer.MAX_VALUE;
for ( int i = 0 ; i < n; i++) {
int sum = calculateSum(arr, n, arr[i]);
res = Math.min(res, sum);
}
return res;
}
public static void main(String[] args) {
int [] arr = { 5 , 11 , 14 , 10 , 17 , 15 };
int n = arr.length;
int minSum = findMinSum(arr, n);
System.out.println(minSum);
}
}
|
Python3
def calculateSum(arr, n, x):
sum = 0
for i in range (n):
sum + = abs (arr[i] - x)
return sum
def findMinSum(arr, n):
res = float ( 'inf' )
for i in range (n):
sum = calculateSum(arr, n, arr[i])
res = min (res, sum )
return res
if __name__ = = '__main__' :
arr = [ 5 , 11 , 14 , 10 , 17 , 15 ]
n = len (arr)
minSum = findMinSum(arr, n)
print (minSum)
|
C#
using System;
class Program {
static int CalculateSum( int [] arr, int n, int x)
{
int sum = 0;
for ( int i = 0; i < n; i++) {
sum += Math.Abs(arr[i] - x);
}
return sum;
}
static int FindMinSum( int [] arr, int n)
{
int res = int .MaxValue;
for ( int i = 0; i < n; i++) {
int sum = CalculateSum(arr, n, arr[i]);
res = Math.Min(res, sum);
}
return res;
}
static void Main()
{
int [] arr = { 5, 11, 14, 10, 17, 15 };
int n = arr.Length;
int minSum = FindMinSum(arr, n);
Console.WriteLine(minSum);
}
}
|
Javascript
function calculateSum(arr, n, x) {
let sum = 0;
for (let i = 0; i < n; i++) {
sum += Math.abs(arr[i] - x);
}
return sum;
}
function findMinSum(arr, n) {
let res = Number.MAX_SAFE_INTEGER;
for (let i = 0; i < n; i++) {
let sum = calculateSum(arr, n, arr[i]);
res = Math.min(res, sum);
}
return res;
}
let arr = [5, 11, 14, 10, 17, 15];
let n = arr.length;
let minSum = findMinSum(arr, n);
console.log(minSum);
|
Time Complexity: O(n*n) as two nested for loops is basically executing in total. Here, n is size of the input array.
Auxiliary Space: O(1) as no extra space has been used.
Efficient Approach:
The idea is based on fact that middle element would cause minimum sum of differences. When there are even number of elements, we can take any of the middle two elements. We can verify this fact by taking few examples.
Implementation:
C++
#include<bits/stdc++.h>
using namespace std;
int absSumDidd( int a[], int n)
{
sort(a,a+n);
int midValue = a[( int )(n / 2)];
int sum = 0;
for ( int i = 0; i < n; i++) {
sum = sum + abs (a[i] - midValue);
}
return sum;
}
int main()
{
int arr[] = { 5, 11, 14, 10, 17, 15 };
int n= sizeof (arr)/ sizeof (arr[0]);
cout<< absSumDidd(arr,n);
}
|
Java
import java.lang.*;
import java.util.*;
public class GFG {
static int absSumDidd( int a[])
{
Arrays.sort(a);
int midValue = a[a.length / 2 ];
int sum = 0 ;
for ( int i = 0 ; i < a.length; i++) {
sum = sum + Math.abs(a[i] - midValue);
}
return sum;
}
public static void main(String[] args)
{
int arr[] = { 5 , 11 , 14 , 10 , 17 , 15 };
System.out.print(absSumDidd(arr));
}
}
|
Python3
def absSumDidd(a, n):
a.sort()
midValue = a[( int )(n / / 2 )]
sum = 0
for i in range (n):
sum = sum + abs (a[i] - midValue)
return sum
arr = [ 5 , 11 , 14 , 10 , 17 , 15 ]
n = len (arr)
print (absSumDidd(arr, n))
|
C#
using System;
class GFG {
static int absSumDidd( int []a)
{
Array.Sort(a);
int midValue = a[a.Length / 2];
int sum = 0;
for ( int i = 0; i < a.Length; i++) {
sum = sum + Math.Abs(a[i] - midValue);
}
return sum;
}
public static void Main()
{
int []arr = { 5, 11, 14, 10, 17, 15 };
Console.Write(absSumDidd(arr));
}
}
|
Javascript
<script>
function absSumDidd(a)
{
a.sort((a, b) => a - b);
var midValue = a[a.length / 2];
var sum = 0;
for ( var i = 0; i < a.length; i++)
{
sum = sum + Math.abs(a[i] - midValue);
}
return sum;
}
var arr = [ 5, 11, 14, 10, 17, 15 ];
document.write(absSumDidd(arr));
</script>
|
PHP
<?php
function absSumDidd( $a , $n )
{
sort( $a );
$midValue = $a [( $n / 2)];
$sum = 0;
for ( $i = 0; $i < $n ; $i ++)
{
$sum = $sum + abs ( $a [ $i ] -
$midValue );
}
return $sum ;
}
$arr = array (5, 11, 14, 10, 17, 15 );
$n = count ( $arr );
echo absSumDidd( $arr , $n );
?>
|
Time Complexity: O(n Log n)
Auxiliary Space: O(1), as we are only using constant space to store some variables.
We can further optimize the above solution to O(n) by using linear time algorithm for median finding.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...