You are given an integer array nums sorted in non-decreasing order.
Build and return an integer arrayresultwith the same length asnumssuch thatresult[i]is equal to the summation of absolute differences betweennums[i]and all the other elements in the array.
In other words, result[i] is equal to sum(|nums[i]-nums[j]|) where 0 <= j < nums.length and j != i (0-indexed).
publicint[]getSumAbsoluteDifferences(int[] nums) {
int n = nums.length;
int[] ans =newint[n];
long sum = Arrays.stream(nums).reduce(0, Integer::sum);
for (int i = 0; i < n; i++) {
ans[i]= Math.abs((int) (sum - n * nums[i]));
}
return ans;
}
We use prefix and suffix sums to efficiently compute the sum of absolute differences for each index. By precomputing cumulative sums from both ends, we can calculate the left and right contributions for each element in constant time.
classSolution {
fungetSumAbsoluteDifferences(nums: IntArray): IntArray {
val n = nums.size
val prefix = IntArray(n)
val suffix = IntArray(n)
prefix[0] = nums[0]
suffix[n-1] = nums[n-1]
for (i in1 until n) {
prefix[i] = prefix[i-1] + nums[i]
suffix[n-i-1] = suffix[n-i] + nums[n-i-1]
}
val ans = IntArray(n)
for (i in0 until n) {
val left = nums[i] * i - prefix[i]
val right = suffix[i] - nums[i] * (n - i - 1)
ans[i] = left + right
}
return ans
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
classSolution:
defgetSumAbsoluteDifferences(self, nums):
n = len(nums)
prefix = [0] * n
suffix = [0] * n
prefix[0] = nums[0]
suffix[n-1] = nums[n-1]
for i in range(1, n):
prefix[i] = prefix[i-1] + nums[i]
suffix[n-i-1] = suffix[n-i] + nums[n-i-1]
ans = [0] * n
for i in range(n):
left = nums[i] * i - prefix[i]
right = suffix[i] - nums[i] * (n - i -1)
ans[i] = left + right
return ans