Array Stabilization
Hazrat Ali
Let instability of the array be the following value: maxi=1nai−mini=1nai.
You have to remove exactly one element from this array to minimize instability of the resulting (n−1)-elements array. Your task is to calculate the minimum possible instability.
The first line of the input contains one integer n (2≤n≤10) — the number of elements in the array a.
The second line of the input contains n integers a1,a2,…,an (1≤ai≤10) — elements of the array a.
Print one integer — the minimum possible instability of the array if you have to remove exactly one element from the array a.
4 1 3 3 7
2
2 1 100000
0
Solution
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector<int> a(n);
for (int i = 0; i < n; i++)
{
cin >> a[i];
}
sort(a.begin(), a.end());
int ans = min(
{
a[n - 1] - a[0],
a[n - 2] - a[0],
a[n - 1] - a[1]
});
cout << ans << endl;
return 0;
}