Topics
The problem asks us to calculate the sum of differences for all pairs such that in a given array.
Idea
We can employ the contribution technique to determine how each element contributes to the final sum. Instead of focusing on pairs, we consider each element individually and figure out its net contribution to the total sum of differences. Let’s first sort the array, as done in the code, which simplifies our analysis. In a sorted array, for any pair of indices with , we know that .
In the sum, will be added when it is the element in a pair with . If , then , so can be . So, there are values of . Thus, is added times.
Now, when is subtracted? is subtracted when it is the element in a pair with . Then can be . There are such values of . Thus, is subtracted times. So, the net contribution of is:
Therefore, the total sum of differences is , where is the sorted array. If the array is already sorted or sorting can be done in linear time (e.g., count sort for a limited range), the overall complexity becomes , otherwise .
Code
void solve() {
int n;
cin >> n;
vector<ll> arr(n);
for (int i = 0; i < n; ++i) {
cin >> arr[i];
}
sort(all(arr));
ll res = 0;
for (int i = 0; i < n; ++i) {
res += (arr[i] * (2 * i - n + 1));
}
cout << res << endl;
}