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

12 May 2023

12 May 2023

Write a program to find minimum sum of absolute difference of given array

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023

## C Program to find minimum sum of absolute difference of given array

#include <stdio.h>

#include <stdlib.h>

#include <limits.h>

int MinAbsDif(int *arr,int n)

{

int ans = INT_MAX,sum ;

for(int i = 0 ; i<n ;i++)

{

sum = 0;

for(int j = 0; j<n ; j++)

{

sum += abs(arr[i] - arr[j]);

}

if(sum < ans)

{

ans = sum;

}

}

return ans;

}

int main()

{

int n;    scanf("%d",&n);

int arr[n];

for(int i = 0 ; i<n ; i++)

{

scanf("%d",&arr[i]);

}

printf("%d",MinAbsDif(&arr,n));

return 0;

}

## C++ Program to find minimum sum of absolute difference of given array

#include <bits/stdc++.h>

using namespace std;

int MinAbsDif(int arr[],int n)

{

int ans = INT_MAX,sum ;

for(int i = 0 ; i<n ;i++)

{

sum = 0;

for(int j = 0; j<n ; j++)

{

sum += abs(arr[i] - arr[j]);

}

ans = min(ans,sum);

}

return ans;

}

int main()

{

int n;    cin>>n;

int arr[n];

for(int i = 0 ; i<n ; i++)

{

cin>>arr[i];

}

cout<<MinAbsDif(arr,n);

return 0;

}

## JAVA Program to find minimum sum of absolute difference of given array

import java.util.*;

import java.lang.*;

import java.io.*;

class Ideone

{

static int MinAbsDif(int arr[],int n)

{

int ans = Integer.MAX_VALUE,sum ;

for(int i = 0 ; i<n ;i++)

{

sum = 0;

for(int j = 0; j<n ; j++)

{

sum += Math.abs(arr[i] - arr[j]);

}

ans = Math.min(ans,sum);

}

return ans;

}

public static void main (String[] args) throws java.lang.Exception

{

Scanner sc=new Scanner(System.in);

int n = sc.nextInt();

int[] arr = new int[n];

for(int i = 0 ; i<n ; i++)

{

arr[i] = sc.nextInt();

}

System.out.print(MinAbsDif(arr,n));

}

}

## PYTHON Program to find minimum sum of absolute difference of given array

import sys

def MinAbsDif(arr,n):

ans = sys.maxsize

for i in range(0,n):

sum = 0;

for j in range(0, n):

sum += abs(arr[i]-arr[j])

ans = min(ans, sum)

return ans;

a = [10, 40, 50, 30, 20]

size = len(a)

print(MinAbsDif(a, size))

If you are from 2023 batch student, Join our Telegram group for placement preparation and coming placement drive updates : https://t.me/talentbattle2023