World's most popular travel blog for travel bloggers.

Abs(sum of differences of elements in a sorted array) = array.Max()-array.Min() Why?

, , No Comments
Problem Detail: 

I just found out by luck that

 Abs(sum of differences of elements in a sorted array) = array.Max()-array.Min()  

For example, Consider a sorted array, {1 43 65 97 98 99 101}

Abs(1-43-55-97-98-99-101)= 101-1

Does anyone know why?

Thanks in Advance.

Asked By : Rajiv

Answered By : ruakh

If you picture these as distances along a road, it should be very intuitive.

If (for example) you start at kilometer #7, then proceed through kilometers #45, #81, and #97, then the distances you travel are 45−7, then 81−45, then 97−81; and the total distance you travel is 97−7. Since the total distance is the sum of the individual distances, 97−7 = (45−7) + (81−45) + (97−81).

This only works for a sorted set, because otherwise you have backtracking, where you cover a certain distance and then "un-cover".

Best Answer from StackOverflow

Question Source : http://cs.stackexchange.com/questions/64115

3200 people like this

 Download Related Notes/Documents

0 comments:

Post a Comment

Let us know your responses and feedback