Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Array element with minimum sum of absolute differences?
In C programming, finding the array element with minimum sum of absolute differences is a classic optimization problem. Given an array of N elements, we need to find a value x that minimizes the sum |a[0] - x| + |a[1] - x| + ... + |a[n-1] - x|.
For example, with array {1, 3, 9, 6, 3}, the optimal x is 3, giving us a sum of |1 - 3| + |3 - 3| + |9 - 3| + |6 - 3| + |3 - 3| = 11.
The key insight is that the median of the array is always the optimal choice for x. When the array size is even, both middle elements will give the same optimal result.
Syntax
int minSum(int arr[], int n); // Returns minimum sum of absolute differences
Algorithm
1. Sort the array in ascending order 2. Find the median element (arr[n/2]) 3. Calculate sum of absolute differences from median 4. Return the minimum sum
Example
Here's a complete C program that finds the minimum sum of absolute differences −
#include <stdio.h>
#include <stdlib.h>
// Comparison function for qsort
int compare(const void *a, const void *b) {
return (*(int*)a - *(int*)b);
}
int minSum(int arr[], int n) {
// Sort the array
qsort(arr, n, sizeof(int), compare);
int sum = 0;
int median = arr[n/2]; // Get median element
// Calculate sum of absolute differences
for(int i = 0; i < n; i++) {
sum += abs(arr[i] - median);
}
return sum;
}
int main() {
int arr[] = {1, 3, 9, 6, 3};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Array: ");
for(int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("<br>");
int result = minSum(arr, n);
printf("Minimum sum of absolute differences: %d<br>", result);
return 0;
}
Array: 1 3 9 6 3 Minimum sum of absolute differences: 11
How It Works
- After sorting: {1, 3, 3, 6, 9}
- Median at index n/2 = 2, which is value 3
- Sum calculation: |1-3| + |3-3| + |3-3| + |6-3| + |9-3| = 2 + 0 + 0 + 3 + 6 = 11
Key Points
- Time complexity: O(n log n) due to sorting
- Space complexity: O(1) for additional space
- The median always minimizes the sum of absolute deviations
- For even-sized arrays, any element between the two middle elements works optimally
Conclusion
The minimum sum of absolute differences problem is efficiently solved using the median property. Sorting the array and choosing the median guarantees the optimal solution with minimal computational overhead.
