All problems

Problem 515

Minimum Difference After Three Changes

Medium · 20 pts · Array, Greedy, Sorting

Problem

You may change at most three elements of the array to any values you like. Find the smallest possible difference between the largest and the smallest element afterwards. With four or fewer elements you can make them all equal, so the answer is 0. Otherwise sort the array: the best plan always changes some of the smallest and some of the largest values, so try the four ways of removing three values from the two ends.

Input

The first line contains an integer N, the size of the array. The second line contains N space-separated integers A[0], A[1], ..., A[N-1].

Output

Print the minimum possible difference.

Constraints

1 <= N <= 100000; -1000000000 <= A[i] <= 1000000000

Example input

5
1 5 0 10 14

Example output

1

Explanation

Sorted, 1 5 0 10 14 is 0 1 5 10 14. Changing 5, 10 and 14 to values between 0 and 1 leaves a difference of 1 - 0 = 1, which is the best of the four options.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Degree of an Array Next: Sum of Subarray Minimums