You are given a sequence a1,a2,…,ana1,a2,…,an consisting of nn integers.
You may perform the following operation on this sequence: choose any element and either increase or decrease it by one.
Calculate the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than kk times.
Input
The first line contains two integers nn and kk (2≤n≤105,1≤k≤1014)(2≤n≤105,1≤k≤1014) — the number of elements in the sequence and the maximum number of times you can perform the operation, respectively.
The second line contains a sequence of integers a1,a2,…,ana1,a2,…,an (1≤ai≤109)(1≤ai≤109).
Output
Print the minimum possible difference between the maximum element and the minimum element in the sequence, if you can perform the aforementioned operation no more than kk times.
Examples
Input
4 5 3 1 7 5Output
2Input
3 10 100 100 100Output
0Input
10 9 4 5 5 7 5 4 5 2 4 3Output
1
Note
In the first example you can increase the first element twice and decrease the third element twice, so the sequence becomes [3,3,5,5][3,3,5,5], and the difference between maximum and minimum is 22. You still can perform one operation after that, but it's useless since you can't make the answer less than 22.
In the second example all elements are already equal, so you may get 00 as the answer even without applying any operations.
题意:有n个数,可执行最多k次操作,每次操作只能对一个数+1或者-1,求执行操作变化后的最大值和最小值的差值(使差值尽量小)。
思路:对数组进行 从小到大排序,比如 数列
1 1 1 2 2 3 5 8 10 10
将最小值和最大值要改变就 需要将所有相同大小的都改变,左相同的数量为L, 右为R。
比较L 和R每次改变小的一边,对于 每部分要改变的值要注意,左变尽量像比 最小值大的 第一个值靠近,右边像比最大值小的第一个值 进行靠近,但注意操作的次数不可大于k。
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long ll;
ll a[100010];
int main()
{
ll n,k;
while(~scanf("%lld%lld",&n,&k))
{
memset(a,0,sizeof(a));
for(int i=1; i<=n; i++)
scanf("%lld",&a[i]);
sort(a+1,a+n+1);
ll l=1,r=n;
ll minn=a[1],maxx=a[n];
ll kk;
while(1)
{
if(minn==maxx)
break;
while(a[l+1]==minn)
l++;
while(a[r-1]==maxx)
r--;
ll xx=l;
ll yy=n-r+1;
if(xx<yy)
{
kk=min(a[l+1]-minn,k/xx);
if(kk==0)
break;
k-=kk*xx;
minn+=kk;
}
else
{
kk=min(maxx-a[r-1],k/yy);
if(kk==0)
break;
k-=kk*yy;
maxx-=kk;
}
}
printf("%lld\n",maxx-minn);
}
return 0;
}