Absolute Values Sum Minimization in JavaScript

In JavaScript, finding the value that minimizes the sum of absolute differences from all elements in an array is a fundamental optimization problem. The optimal solution is to find the median of the array.

Understanding the Problem

Given an array of numbers, we need to find a value x that minimizes the sum of |arr[i] - x| for all elements in the array. Mathematically, this optimal value is always the median of the sorted array.

Sum Minimization Concept 1 3 5 7 9 Median = 5 Minimizes: |1-5| + |3-5| + |5-5| + |7-5| + |9-5| = 12

Algorithm

Step 1: Sort the array in ascending order to find the median efficiently.

Step 2: For odd-length arrays, return the middle element. For even-length arrays, return the element at index (length/2) - 1 (the lower median).

Implementation

function sumMinimization(arr) {
   // Sort the array in ascending order
   arr.sort((a, b) => a - b);
 
   // Check if the array length is odd or even
   if (arr.length % 2 === 1) {
     // For odd-length array, return middle element
     return arr[Math.floor(arr.length / 2)];
   } else {
     // For even-length array, return lower median
     return arr[(arr.length / 2) - 1];
   }
}

// Example with odd-length array
const array1 = [1, 2, 3, 4, 5];
const result1 = sumMinimization(array1);
console.log("Odd array:", result1);

// Example with even-length array
const array2 = [2, 8, 4, 6];
const result2 = sumMinimization(array2);
console.log("Even array:", result2);
Odd array: 3
Even array: 4

Why the Median Works

// Verification example
function calculateSum(arr, x) {
   return arr.reduce((sum, val) => sum + Math.abs(val - x), 0);
}

const testArray = [1, 3, 5, 7, 9];
const median = 5;

console.log("Sum using median (5):", calculateSum(testArray, median));
console.log("Sum using value 4:", calculateSum(testArray, 4));
console.log("Sum using value 6:", calculateSum(testArray, 6));
Sum using median (5): 12
Sum using value 4: 14
Sum using value 6: 14

Complexity Analysis

Aspect Complexity Reason
Time O(n log n) Array sorting operation
Space O(1) Only using constant extra space

Conclusion

The median of a sorted array provides the optimal solution for minimizing the sum of absolute differences. This approach leverages the mathematical property that the median minimizes the sum of absolute deviations.

Updated on: 2026-03-15T23:19:00+05:30

678 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements