ABSP1 - abs(a-b) I

no tags 

Recently Mr. Kopa Samsu is learning programming. On a very renowned online judge, he found a problem:

You are given an array of N numbers in non-decreasing order. You have to answer the summation of the absolute difference of all distinct pairs in the given array.

Do you know what distinct pair means? Suppose you have an array of 3 elements: 3 5 6

Then all the distinct pairs are:

3 5
3 6
5 6

For this problem, Mr. Kopa Samsu implemented an algorithm to find the summation of the absolute difference of all distinct pairs. His algorithm was:

int ABS(int a[], int n)
    int sum = 0;
    for (int i = 1; i <= n ;i++)
        for (int j = i + 1; j <= n; j++)
            sum += abs(a[i] - a[j]);

After a great hard work, he finished the code. But alas!!! Frustration came around him when he submitted his code, the judge gave the verdict “TLE” (Time Limit Exit). “How can I get rid of TLE?” he thought a lot but couldn't find any way. Then suddenly, he remembered about you that you (his friend) is very good at programming. So, he came to you seeking your help. Can you help him solving this problem?


The input data set starts with an integer T (T <= 1000), the number of test cases. Then every test case starts with a integer N (N <= 10000), the number of elements in the array. After that, the next line contains N integers A[i], where 1 <= i <= N and 1 <= A[i] <= 1000000000 & A[i] <= A[i+1].


Every test case should output an integer “X”, where X is the summation of the absolute difference of all the distinct pair.


1 2 3
1 4 5
2 4 6

Problem Set: S.M. Shaheen Sha, Raihat Zaman Neloy
Data Set & Solution: Raihat Zamane Neloy

hide comments
shikhar_may7: 2019-10-14 15:03:26

Observation : each a[i] is added i times and is subtracted n-i-1 times. :)

sonuexpc: 2019-10-01 16:14:25

use long long int instead of int cost me 1 WA :(

angryninja: 2019-09-04 22:47:39

Distinct pairs don't mean different nos, it means different index. (As said by @sktibrewal)

Last edit: 2019-09-04 22:48:19
a_l_o_n_e: 2019-08-25 19:35:17

AC in one go!!!

syed_tanveer: 2019-04-17 09:10:13

AC with 0.00s :)

sandeep48: 2019-01-07 06:05:40

no need to declare array
observe pattern and apply maths
cost me 0.05 in one go

deependra_18: 2019-01-02 16:36:15

for this quesn don't trust spoj toolkit

vipul_17: 2018-09-16 13:12:14

AC with 0.05..:)

vengatesh15: 2018-08-12 20:22:46

think reverse

anirudnits: 2018-07-20 21:19:31

don't trust spoj toolkit for this one

Added by:Raihat Zaman Neloy
Time limit:1s
Source limit:50000B
Memory limit:1536MB
Cluster: Cube (Intel G860)
Languages:All except: ASM64