#K91002. Minimize Absolute Differences with Uniform Shift
Minimize Absolute Differences with Uniform Shift
Minimize Absolute Differences with Uniform Shift
You are given two arrays (A = [A_1, A_2, \dots, A_n]) and (B = [B_1, B_2, \dots, B_n]) of length (n). You are allowed to perform a uniform modification on array (B): choose an integer (x) (which may be positive, negative, or zero) and add it to every element of (B). After this operation, array (B) becomes (B' = [B_1+x, B_2+x, \dots, B_n+x]).
The goal is to choose (x) such that the sum of absolute differences [ S(x) = \sum_{i=1}^{n} \left| A_i - (B_i + x) \right| ] is minimized.
A well known fact in optimization is that the function (S(x)) is minimized when (x) is chosen so that it offsets the median of the differences (D_i = A_i - B_i). In other words, if you let (m) be the median of ({D_1, D_2, \dots, D_n}), then the minimum possible sum is [ S_{min} = \sum_{i=1}^{n} \left| D_i - m \right|. ]
Your task is to compute (S_{min}) given arrays (A) and (B).
inputFormat
The input is read from standard input (stdin) and consists of three lines:
- The first line contains an integer (n) ((1 \le n \le 10^5)), the number of elements in each array.
- The second line contains (n) space-separated integers representing array (A).
- The third line contains (n) space-separated integers representing array (B).
outputFormat
Output to standard output (stdout) a single integer: the minimum possible sum of absolute differences after applying the optimal uniform modification to array (B).## sample
3
1 3 5
2 6 8
2
</p>