Problem · Sorting

Minimum Difference Sum

Learn this problem
EasyOracle logoOracleFULLTIMEOA

Problem statement

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.

Function

minDiff(arr: int[]) → int

Complete the function minDiff in the editor.

minDiff has the following parameter:

  1. int arr[]: an integer array

Returns

int: the sum of the absolute differences of adjacent elements

Examples

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

drafts saved locally
public int minDiff(int[] arr) {
    // write your code here
}
arr[1, 3, 3, 2, 4]
expected3
checking account