Мінімальна сума різниць#11779

Мінімальна сума різниць (Розбір)

We can see that It's optimal to use sorting greedy.

Proof : Sorting minimizes the gaps between consecutive numbers and thus \sum_{i=1}^{n-1} |a_{i+1}-a_i| is minimized as well.

Complexity

n=int(input())
a=list(map(int,input().split()))
a.sort()
ans=0
for i in range(n-1):
    ans+=a[i+1]-a[i]
print(ans)