Find the sum of minimum absolute difference of the given array

Find the sum of minimum absolute difference of the given array

The program to find the sum of the minimum absolute difference of the array is discussed here. An array of distinct elements is given as input and the sum of the minimum absolute difference of each array element has to be found. The minimum absolute difference is calculated using the formula,


Finding the Sum of Minimum Absolute Difference of the given Array

Minimum Absolute Difference (a) = min(abs(a arr[j])) ; where 1 <= j <= n and j != i, abs is the absolute value.

For example, consider the following array given as input: arr = {1, 3, 9, 3, 6}

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 = 11

Output: 11


Finding the Sum of Minimum Absolute Difference of the given Array

Algorithm

  • The given input array is sorted.
  • For the first element of the array, its minimum absolute difference is calculated using the second array element.
  • For the last array element, its minimum absolute difference is calculated using the second last array element.
  • For the other array elements, the minimum absolute difference for an element at the index is calculated as follows:
  • minAbsDiff= min( abs(arr[i] arr[i-1]), abs(ar[i] arr[i+1]) ).

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

@@coding::1@@

Time complexity: O(n)


Finding the Sum of Minimum Absolute Difference of the given Array



Recommended Programs








Finding the Sum of Minimum Absolute Difference of the given Array

c