Regarding your question ZCO13001 ,you can do the following-
- Sort the array
- Find out the difference between last and second last element. Add it to answer.
- Now find difference between third last and second last element. Now, can we deduce the difference between third last and last element on basis of this? Yes, number of terms with which we have to calculate difference (=end index-start index-1)=(n-1-(n-3)-1)=1. And we know that Difference b/w 3rd last and last term= Diff b/w 3rd last and 2nd last+ Difference b/w 2nd last and 3rd last.
- Now think in terms of calculating the difference with just knowledge of number of elements, and difference between i and (i+1)'th term. Lets take an example array to highlight it.
Let arr={3,3,5,7,10}. Now, difference between last and 2nd last term= 10-7 =3. Thats the answer had the array been just {7,10}.
Now, consider {5,7,10}. The answer is (2+5)+(3)=10. Can we find a relation between previous answer and this answer? Yes we can!
We know that difference between 5 and 7 is 2. We also know that answer of array {7,10} is 3. Now, the new terms added are nothing but (7-5) and (10-5) to the answer.
Now see this, difference between 7 and 5 is 2. Also, number of terms, excluding 7, is 1. We know that difference of all such terms = 2+difference of that term with 7. Can we make a formula out of it?
Lets say you are at i’th term. We know the difference between i and (i+1)'th term. We also know the number of terms in interval (i+1,n]. We also know answer upto (i+1) from end, or sum of difference of terms in [i+1,n].
Now I claim that, using this, I can say that-
Newly added terms in ans= (arr[i+1]-arr[i])+(arr[i+2]-arr[i])…(arr[n-1]-arr[i])
and-
difference = arr[i+1]-arr[i].
==>arr[i]=arr[i+1]-difference.
Proceed further with substitution and find relation between previous and new answer. The code snippet is given to cross check and must be seen only after you give an attempt.
int i,j,k;
for(i=0;i<n;i++)cin>>arr[i];
sort(arr,arr+n);
long long int ans=0,add=0,diff=0;
for(i=n-2;i>=0;i--)
{
if(arr[i]!=arr[i+1])
{
diff=arr[i+1]-arr[i];
add+=(n-1-i)*(arr[i+1]-arr[i]);
}
ans+=add;
//cout<<"diff="<<diff<<" ans="<<ans<<" add="<<add<<endl;
}
cout<<ans<<endl;