思路:二分一个最小值,然后再二分一个最大值,因为会加k,使得小于那个最小值的数都加成为大于等于他的数

你会减去k,使得大于那个数,都降为小于等于的那个数



#include<bits\stdc++.h>
using namespace std;
#define LL long long
const int maxn = 5e5+7;
int a[maxn];

int main()
{
     int n,k;
	 LL sum = 0;
	 scanf("%d%d",&n,&k);
	 for (int i = 1;i<=n;i++)
		 scanf("%d",&a[i]),sum+=a[i];
	 sort(a+1,a+1+n);
	 int ll = sum/n;
	 int rr = (sum+n-1)/n;
	 int l = 0,r=ll,ans1=0;
	 while(l<=r)
	 {
		 int m = (l+r)>>1;
		 LL ne = 0;
		 for (int i= 1;i<=n;i++)
			 if(a[i]<=m)
				 ne+=m-a[i];
		 if (ne <= k)
			 ans1=m,l=m+1;
		 else
			 r=m-1;
	 }
	 l = rr,r=1e9;
	 int ansr = 0;
	 while(l<=r)
	 {
		 int m = (l+r)>>1;
		 LL ne = 0;
		 for (int i = 1;i<=n;i++)
			 if (a[i]>m)
				 ne+=a[i]-m;
		 if (ne <= k)
			 ansr = m,r=m-1;
		 else
			 l=m+1;
	 }
	 printf("%d\n",ansr-ans1);
}




Description



We all know the impressive story of Robin Hood. Robin Hood uses his archery skills and his wits to steal the money from rich, and return it to the poor.

There are n citizens in Kekoland, each person has ci coins. Each day, Robin Hood will take exactly 1 coin from the richest person in the city and he will give it to the poorest person (poorest person right after taking richest's 1 coin). In case the choice is not unique, he will select one among them at random. Sadly, Robin Hood is old and want to retire in k

After taking his money are taken by Robin Hood richest person may become poorest person as well, and it might even happen that Robin Hood will give his money back. For example if all people have same number of coins, then next day they will have same number of coins too.

Your task is to find the difference between richest and poorest persons wealth after k



Input



The first line of the input contains two integers n and k (1 ≤ n ≤ 500 000, 0 ≤ k ≤ 109) — the number of citizens in Kekoland and the number of days left till Robin Hood's retirement.

The second line contains n integers, the i-th of them is ci (1 ≤ ci ≤ 109) — initial wealth of the i-th person.



Output



Print a single line containing the difference between richest and poorest peoples wealth.



Sample Input



Input



4 1 1 1 4 2



Output



2



Input



3 1 2 2 2



Output



0