Minimum sum of differences#11779

Minimum sum of differences

1 sekunt
256 megabaýt
Örän ýeňil

Given an array of integers of length . Find a permutation of the array elements such that the sum of the absolute differences between adjacent elements is minimized. In other words, find the order of the elements of the array such that the value of |A_1 - A_2| + |A_2 - A_3| + \ldots + |A_{N-1} - A_N| is minimized.

Giriş

The first line contains an integer (2 \le N \le 10^5) – the number of elements in the array.

The second line contains integers A_1, A_2, ..., A_N (-10^5 \le A_i \le 10^5, 1 \le i \le N) separated by spaces.

Çykyş

Print a single number – the minimum sum of the absolute differences between adjacent elements for the optimal permutation of the array.

Mysallar

1-nji mysal

Loading
Loading

Bellik

Optimal permutation of the array:

[4, 2, 1] or [1, 2, 4].

Sum of differences:

|4 - 2| + |2 - 1| = 3