Блог пользователя vedprakashsingh216

Автор vedprakashsingh216, история, 16 месяцев назад, По-английски

How to Quickly Calculate the Total Absolute

for (int i = 0; i < n; ++i) {
    total += 1LL * a[i] * (2 * i - n + 1);
}

Differences Over All Pairs (Without Brute Force!)

Hey everyone!

While solving a problem recently, I found a really useful trick for calculating the sum of absolute differences between all pairs in a sorted array.

Say you have a sorted array like:

a = [1, 3, 6]

You want to compute:

|1 - 3| + |1 - 6| + |3 - 6| = 2 + 5 + 3 = 10

Just loop through the array once and compute this. Much faster than brute force!


Why This Works (Simple Explanation)

Let’s understand this in plain English — no complex math needed!

Each number in the array: - Will be subtracted from numbers after it. - Will subtract numbers before it.

So every number is: - Subtracted from n - 1 - i elements after it. - Added to i elements before it.

This means the net effect of a[i] is: ~~~~~ a[i] * (i — (n — 1 — i)) = a[i] * (2i — n + 1) ~~~~~

You just loop through the array and apply that for each element.


Example

Let’s try with a = [1, 3, 6]:

You just loop through the array and apply that for each element.


Example

Let’s try with a = [1, 3, 6]: ~~~~~ i = 0 → 1 * (20 — 3 + 1) = 1 * (-2) = -2 i = 1 → 3 * (21 — 3 + 1) = 3 * 0 = 0 i = 2 → 6 * (2*2 — 3 + 1) = 6 * 2 = 12

Sum = -2 + 0 + 12 = 10 ~~~~~

sort(a.begin(), a.end());
long long total = 0;
for (int i = 0; i < n; ++i) {
    total += 1LL * a[i] * (2 * i - n + 1);
}
  • Проголосовать: нравится
  • -28
  • Проголосовать: не нравится

»
16 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Thank you bro, was searching for this topic for hoursss

»
16 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Some additions

int ans = 0;
sort(nums.begin(), nums.end());
for (int i = 1; i < n; i++) ans += (nums[i] - nums[i - 1]) * i * (n - i);
cout << ans << '\n';

This is the same as above but in a more generic way More specifically If we are given a problem that over an array a we need the sum of all pairwise absolute differences we can use the above code