You are given n sticks with positive integral length a1,a2,…,an.
You can perform the following operation any number of times (possibly zero):
choose one stick, then either increase or decrease its length by 1. After each operation, all sticks should have positive lengths.
What is the minimum number of operations that you have to perform such that it is possible to select three of the n sticks and use them without breaking to form an equilateral triangle?An equilateral triangle is a triangle where all of its three sides have the same length.
Input
The first line of the input contains a single integer t (1≤t≤100) — the number of test cases. The description of the test cases follows.The first line of each test case contains a single integer n (3≤n≤300) — the number of sticks.
The second line of each test case contains n integers a1,a2,…,an (1≤ai≤109) — the lengths of the sticks.
It is guaranteed that the sum of n over all test cases does not exceed 300.
Output
For each test case, print one integer on a single line — the minimum number of operations to be made.Example
input
4
3
1 2 3
4
7 3 7 3
5
3 4 2 1 1
8
3 1 4 1 5 9 2 6
output
2
4
1
1
题意:在数组中任选一个数+1或-1,求让数组中至少存在三个相同的数的最小操作次数。
假设有a, b, c三个数(a<=b<=c),如果要让a,b,c三个数相等,最小操作次数为 b-a + c-b = c - a
当c和a差距最小时,操作次数最小,所以先对数组从小到大排序(从大到小也行), 求出每个三元组(a, b, c)中最小的c-a即可。
代码:
#include<iostream>
#include<algorithm>
using namespace std;
int nums[305];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0), cout.tie(0);
int t;
cin >> t;
while(t --)
{
int n, ans = 0x3f3f3f3f;
cin >> n;
for(int i=0; i<n; i++) cin >> nums[i];
sort(nums, nums+n);
for(int i=2; i<n; i++)
ans = min(ans, nums[i]-nums[i-2]); //求三元组(nums[i-2], nums[i-1], nums[i]) nums[i] - nums[i-2] 最小的
cout << ans << endl;
}
return 0;
}