You are given a sequence a1,a2,…,an consisting of n 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 k times.
Input
The first line contains two integers n and k (2≤n≤10 5 ^5 5,1≤k≤10 14 ^{14} 14)(2≤n≤10 5 ^5 5,1≤k≤10 14 ^{14} 14) — 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≤10 9 ^9 9)(1≤ai≤10 9 ^9 9).
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 k times.
Examples
input
Copy
4 5
3 1 7 5
output
Copy
2
input
Copy
3 10
100 100 100
output
Copy
0
input
Copy
10 9
4 5 5 7 5 4 5 2 4 3
output
Copy
1
题意:给定一个序列n和一个数k,对序列进行不超过k次变换,每次变换可以对一个数加一或者减一,使序列的极差最小。
思路:每次变换时,只能变换最小值或最大值,最大值个数如果少于最小值个数,则变换最大值,每次变换与前一个数的差,即k/ansl和a[l+1]-minn的最小值,反之亦然。结束条件为最小值等于最大值,但如果变换次数少于最少变换数时跳出循环,例如最后剩下3个5和4个7,但只有一次变换次数了,此时跳出循环。
代码:
#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
typedef long long ll;
ll a[100005];
int main()
{
ll n,k;
scanf("%I64d%I64d",&n,&k);
for(int i=1;i<=n;i++)
scanf("%I64d",&a[i]);
sort(a+1,a+n+1);
ll minn=a[1],maxx=a[n];
ll l=1,r=n;
while(1)
{
if(maxx==minn)break;
while(minn==a[l+1])l++;
while(maxx==a[r-1])r--;
ll ansl=l,ansr=n-r+1;
if(ansl<ansr)
{
ll p=min(k/(ansl),a[l+1]-minn);
if(p==0)break;
k-=p*ansl;
minn+=p;
}
else
{
ll p=min(k/ansr,maxx-a[r-1]);
if(p==0)break;
k-=p*ansr;
maxx-=p;
}
}
printf("%I64ld\n",maxx-minn);
return 0;
}