![]() |
VOOZH | about |
Given an array of n distinct integers. The task is to find the sum of minimum absolute difference of each array element. For an element arr[i] present at index i in the array, its minimum absolute difference is calculated as:
Examples:
Input : arr = [4, 1, 5]
Output : 5
Explanation: Sum of minimum absolute differences is |4-5| + |1-4| + |5-4| = 1 + 3 + 1 = 5
Input : arr = [5, 10, 1, 4, 8, 7]
Output : 9
Explanation: Sum of minimum absolute differences is
|5-4| + |10-8| + |1-4| + |4-5| + |8-7| + |7-8| = 1 + 2 + 3 + 1 + 1 + 1 = 9
Input : arr = [12, 10, 15, 22, 21, 20, 1, 8, 9]
Output : 18
The idea is to iterate through each element in the array and find the minimum absolute difference between that element and any other element in the array. For each element, we check all other elements, find the smallest absolute difference, and add it to our sum.
5
The idea is to sort the array first so that elements with similar values are placed adjacently. After sorting, for any element, its minimum absolute difference will be with either its left neighbor or its right neighbor.
Step by step approach:
5