Sum of Absolute Differences
Given an array of integers, compute the sum of absolute differences between each element and every other element in the array. The absolute difference between two integers a and b is given by |a - b|, where |x| denotes the absolute value of x.
[ 1, 2, 3 ]
Explanation. The absolute differences are |1-2|=1, |1-3|=2, and |2-3|=1. So the sum is 1+2+1+1+2+1=6.
[ 10, 12 ]
Explanation. Since there are only two elements, the sum of the absolute differences is |10-12|=2.
[ 5, -3, 6 ]
Explanation. Calculating each pair's absolute difference results in |5+3|=8, |5-6|=1, |-3-6|=9. Sum for all pairs is 8+1+9+8+1+1=28.
Follow-up: Can you solve this problem in an optimized way to reduce computational redundancy?
The input array will have at least two integers and at most 100 integers, each within the range -1000 to 1000.
- Views
- 2