Sum of Absolute Differences
Given a sorted array of distinct integers, create an array where each element i is the sum of the absolute differences between the number at index i in the original array and every other number in the array.
[ 1, 2, 3 ]
Explanation. For index 0 (element 1): |1-2| + |1-3| = 1 + 2 = 3; For index 1 (element 2): |2-1| + |2-3| = 1 + 1 = 2; For index 2 (element 3): |3-1| + |3-2| = 2 + 1 = 3. Output array is [3, 2, 3].
[ -10, 0, 10 ]
Explanation. Each element has a total difference of 20 with all other elements.
[ 5, 7, 12, 100 ]
Explanation. Calculating absolute differences for each element results in the output sums: 111 for index 0, 107 for index 1, 93 for index 2, and 19 for index 3.
Follow-up: Can the problem be solved in linear time complexity, considering the array is already sorted?
The input array will contain at least two elements and will not exceed 1,000 elements. Each element in the array is between -1,000,000 and 1,000,000.
- Views
- 3