Minimizing Difference

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值