[LeetCode] Sum of Absolute Differences in a Sorted Array

1685. Sum of Absolute Differences in a Sorted Array

You are given an integer array nums sorted in non-decreasing order.

Build and return an integer array result with the same length as nums such that result[i] is equal to the summation of absolute differences between nums[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).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:
vector<int> getSumAbsoluteDifferences(vector<int>& nums) {
vector<int> psum1(10101, 0), psum2(10101, 0), psum3(10101,0);
for(auto& n : nums) {
psum1[n] += n;
psum2[n] += n;
psum3[n] += 1;
}
for(int i = 1; i < 10101; i++) {
psum1[i] += psum1[i-1];
psum3[i] += psum3[i-1];
}
for(int i = 10098; i >= 0; i--) {
psum2[i] += psum2[i+1];
}
vector<int> res;
for(auto& n : nums) {
long long l = psum1[n], lcnt = psum3[n];
long long r = psum2[n+1], rcnt = nums.size() - lcnt;
res.push_back(n * lcnt - l + r - n * rcnt);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/08/17/PS/LeetCode/sum-of-absolute-differences-in-a-sorted-array/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.