Problem · Sorting
Minimum Difference Sum
Given an array of n integers, rearrange them so that the sum of the absolute differences of all adjacent elements is minimized. Then, compute the sum of those absolute differences.
Complete the function minDiff in the editor.
minDiff has the following parameter:
int arr[]: an integer array
Returns
int: the sum of the absolute differences of adjacent elements
Examples
01 · Example 1
arr = [1, 3, 3, 2, 4] return = 3
If the list is rearranged as arr' = [1, 2, 3, 3, 4], the absolute differences are |1 - 2| = 1, |2 - 3| = 1, |3 - 3| = 0, |3 - 4| = 1. The sum of those differences is 1 + 1 + 0 + 1 = 3.
Constraints
- 2 ≤ n ≤ 10^5
- 0 ≤ arr[i] ≤ 10^9, where 0 ≤ i < n
More Oracle problems
public int minDiff(int[] arr) {
// write your code here
}
arr[1, 3, 3, 2, 4]
expected3
sign in to submit