You are given a sequence $a_1, a_2, \dots, a_n$ 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 \le n \le 10^{5}, 1 \le k \le 10^{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 $a_1, a_2, \dots, a_n$ $(1 \le a_i \le 10^{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
4 5
3 1 7 5

Output
2

Input
3 10
100 100 100

Output
0

Input
10 9
4 5 5 7 5 4 5 2 4 3

Output
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]$, and the difference between maximum and minimum is $2$. You still can perform one operation after that, but it's useless since you can't make the answer less than $2$.

In the second example all elements are already equal, so you may get $0$ as the answer even without applying any operations.

Difficulty: HARD
Tags: Sorting

Constructive algorithms

Amortized analysis

Greedy algorithms
Skill types: Sorting

Amortized analysis

Greedy algorithms

Starter code:

Solutions:
(n, k) = [int(x) for x in input().split()]
a = [int(x) for x in input().split()]
d = {}
for x in a:
	if x not in d:
		d[x] = 0
	d[x] += 1
nums = list(d.keys())
nums.sort()
l = 0
r = len(nums) - 1
while l < r:
	if d[nums[l]] < d[nums[r]]:
		cur = nums[l]
		nxt = nums[l + 1]
		full_cost = (nxt - cur) * d[cur]
		if full_cost <= k:
			d[nxt] += d[cur]
			k -= full_cost
			l += 1
		else:
			mx = k // d[cur]
			nums[l] += mx
			break
	else:
		cur = nums[r]
		nxt = nums[r - 1]
		full_cost = (cur - nxt) * d[cur]
		if full_cost <= k:
			d[nxt] += d[cur]
			k -= full_cost
			r -= 1
		else:
			mx = k // d[cur]
			nums[r] -= mx
			break
print(nums[r] - nums[l])


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve1(b, n, k):
	sl = 0
	sr = 0
	for i in b:
		sr += i[0] * i[1]
	i = 0
	j = 0
	m = len(b)
	nl = 0
	nr = n
	r = int(2 * 1000000000.0 + 5)
	while i < m:
		sl += b[i][0] * b[i][1]
		nl += b[i][1]
		while j < m - 1 and (j < i or b[i][0] * nl - sl + sr - b[j][0] * nr > k):
			sr -= b[j][0] * b[j][1]
			nr -= b[j][1]
			j += 1
		hm = k - (b[i][0] * nl - sl + sr - b[j][0] * nr)
		if hm < 0:
			break
		if i == j:
			return 0
		if i < j:
			r = min(r, b[j][0] - min(b[i][0] + hm // nl, b[i + 1][0]))
			r = min(r, max(b[j][0] - hm // nr, b[j - 1][0]) - b[i][0])
		i += 1
	return r

def solve():
	(n, k) = mints()
	a = list(mints())
	a.sort()
	b = []
	i = 0
	while i < n:
		j = i + 1
		while j < n and a[j] == a[i]:
			j += 1
		b.append((a[i], j - i))
		i = j
	r1 = solve1(b, n, k)
	b.reverse()
	for i in range(len(b)):
		b[i] = (-b[i][0], b[i][1])
	print(min(r1, solve1(b, n, k)))
solve()


from collections import deque
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
q = deque()
prev = a[0]
count = 1
for i in range(1, n):
	if a[i] == prev:
		count += 1
	else:
		q.append([prev, count])
		prev = a[i]
		count = 1
q.append([prev, count])
j = len(q) - 1
while k and j > 0:
	if q[0][1] < q[j][1]:
		x = q.popleft()
		diff = q[0][0] - x[0]
		if diff * x[1] <= k:
			k -= diff * x[1]
			q[0][1] += x[1]
			j -= 1
		else:
			q.appendleft([x[0] + k // x[1], x[1]])
			break
	else:
		x = q.pop()
		diff = x[0] - q[-1][0]
		if diff * x[1] <= k:
			k -= diff * x[1]
			q[-1][1] += x[1]
			j -= 1
		else:
			q.append([x[0] - k // x[1], x[1]])
			break
print(q[-1][0] - q[0][0])


import sys
import bisect
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = list(map(int, input().split()))

def f(a):
	a.sort()
	pref = a[:]
	for i in range(1, n):
		pref[i] += pref[i - 1]
	mx = a[-1]

	def possible(base, x):
		idx = bisect.bisect_left(a, x + 1)
		need = pref[-1] - (pref[idx - 1] if idx >= 1 else 0) - (n - idx) * x
		return need + base <= k
	ans = 1 << 32
	for lo in set(a):
		idx = bisect.bisect_left(a, lo)
		base = lo * (idx + 1) - pref[idx]
		if base > k:
			break
		(hi0, hi1) = (lo, mx)
		if possible(base, hi0):
			print(0)
			exit()
		while hi0 + 1 < hi1:
			mid = (hi0 + hi1) // 2
			if possible(base, mid):
				hi1 = mid
			else:
				hi0 = mid
		ans = min(ans, hi1 - lo)
	return ans
print(min(f(a), f([-x for x in a])))


(n, k) = map(int, input().split(' '))
arr = list(map(int, input().split(' ')))
arr.sort()
dif = [0] * n
for i in range(n - 1):
	dif[i] = arr[i + 1] - arr[i]
i = 0
j = n - 2
left = 1
right = 1
last = -1
while k > 0 and i <= j:
	if dif[i] == 0:
		left += 1
		i += 1
		continue
	if dif[j] == 0:
		right += 1
		j -= 1
		continue
	if i == j:
		last = i
	if left <= right:
		difToSubstract = min(dif[i], k // left)
		if difToSubstract == 0:
			k = 0
			break
		k -= left * difToSubstract
		dif[i] -= difToSubstract
	else:
		difToSubstract = min(dif[j], k // right)
		if difToSubstract == 0:
			k = 0
			break
		k -= right * difToSubstract
		dif[j] -= difToSubstract
if i <= j:
	sol = 0
	for u in range(i, j + 1):
		sol += dif[u]
	print(sol)
else:
	print(dif[last])


import sys
(n, k) = list(map(int, input().split()))
num = [int(x) for x in input().split()]
num.sort()
if n == 1:
	print(0)
	return
pre = 0
pree = num[0]
lat = n - 1
latt = num[n - 1]
pren = 1
latn = 1
while k > 0:
	while num[pre + 1] == pree and pre + 1 < lat:
		pre += 1
		pren += 1
	while num[lat - 1] == latt and pre < lat - 1:
		lat -= 1
		latn += 1
	if pren > k and latn > k:
		break
	if pree < latt:
		if pren < latn:
			if pren * (num[pre + 1] - num[pre]) <= k:
				k -= pren * (num[pre + 1] - num[pre])
				pre += 1
				pren += 1
				pree = num[pre]
			else:
				pree += k // pren
				k %= pren
		elif latn * (num[lat] - num[lat - 1]) <= k:
			k -= latn * (num[lat] - num[lat - 1])
			lat -= 1
			latn += 1
			latt = num[lat]
		else:
			latt -= k // latn
			k %= latn
	else:
		break
print(latt - pree)


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

class TreeNode:

	def __init__(self, k, v):
		self.key = k
		self.value = v
		self.left = None
		self.right = None
		self.parent = None
		self.height = 1
		self.num_left = 1
		self.num_total = 1

class AvlTree:

	def __init__(self):
		self._tree = None

	def add(self, k, v):
		if not self._tree:
			self._tree = TreeNode(k, v)
			return
		node = self._add(k, v)
		if node:
			self._rebalance(node)

	def _add(self, k, v):
		node = self._tree
		while node:
			if k < node.key:
				if node.left:
					node = node.left
				else:
					node.left = TreeNode(k, v)
					node.left.parent = node
					return node.left
			elif node.key < k:
				if node.right:
					node = node.right
				else:
					node.right = TreeNode(k, v)
					node.right.parent = node
					return node.right
			else:
				node.value = v
				return

	@staticmethod
	def get_height(x):
		return x.height if x else 0

	@staticmethod
	def get_num_total(x):
		return x.num_total if x else 0

	def _rebalance(self, node):
		n = node
		while n:
			lh = self.get_height(n.left)
			rh = self.get_height(n.right)
			n.height = max(lh, rh) + 1
			balance_factor = lh - rh
			n.num_total = 1 + self.get_num_total(n.left) + self.get_num_total(n.right)
			n.num_left = 1 + self.get_num_total(n.left)
			if balance_factor > 1:
				if self.get_height(n.left.left) < self.get_height(n.left.right):
					self._rotate_left(n.left)
				self._rotate_right(n)
			elif balance_factor < -1:
				if self.get_height(n.right.right) < self.get_height(n.right.left):
					self._rotate_right(n.right)
				self._rotate_left(n)
			else:
				n = n.parent

	def _remove_one(self, node):
		replacement = node.left or node.right
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = replacement
			else:
				node.parent.right = replacement
			replacement.parent = node.parent
			node.parent = None
		else:
			self._tree = replacement
			replacement.parent = None
		node.left = None
		node.right = None
		node.parent = None
		self._rebalance(replacement)

	def _remove_leaf(self, node):
		if node.parent:
			if AvlTree._is_left(node):
				node.parent.left = None
			else:
				node.parent.right = None
			self._rebalance(node.parent)
		else:
			self._tree = None
		node.parent = None
		node.left = None
		node.right = None

	def remove(self, k):
		node = self._get_node(k)
		if not node:
			return
		if AvlTree._is_leaf(node):
			self._remove_leaf(node)
			return
		if node.left and node.right:
			nxt = AvlTree._get_next(node)
			node.key = nxt.key
			node.value = nxt.value
			if self._is_leaf(nxt):
				self._remove_leaf(nxt)
			else:
				self._remove_one(nxt)
			self._rebalance(node)
		else:
			self._remove_one(node)

	def get(self, k):
		node = self._get_node(k)
		return node.value if node else -1

	def _get_node(self, k):
		if not self._tree:
			return None
		node = self._tree
		while node:
			if k < node.key:
				node = node.left
			elif node.key < k:
				node = node.right
			else:
				return node
		return None

	def get_at(self, pos):
		x = pos + 1
		node = self._tree
		while node:
			if x < node.num_left:
				node = node.left
			elif node.num_left < x:
				x -= node.num_left
				node = node.right
			else:
				return (node.key, node.value)
		raise IndexError('Out of ranges')

	@staticmethod
	def _is_left(node):
		return node.parent.left and node.parent.left == node

	@staticmethod
	def _is_leaf(node):
		return node.left is None and node.right is None

	def _rotate_right(self, node):
		if not node.parent:
			self._tree = node.left
			node.left.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.left
			node.left.parent = node.parent
		else:
			node.parent.right = node.left
			node.left.parent = node.parent
		bk = node.left.right
		node.left.right = node
		node.parent = node.left
		node.left = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	def _rotate_left(self, node):
		if not node.parent:
			self._tree = node.right
			node.right.parent = None
		elif AvlTree._is_left(node):
			node.parent.left = node.right
			node.right.parent = node.parent
		else:
			node.parent.right = node.right
			node.right.parent = node.parent
		bk = node.right.left
		node.right.left = node
		node.parent = node.right
		node.right = bk
		if bk:
			bk.parent = node
		node.height = max(self.get_height(node.left), self.get_height(node.right)) + 1
		node.num_total = 1 + self.get_num_total(node.left) + self.get_num_total(node.right)
		node.num_left = 1 + self.get_num_total(node.left)

	@staticmethod
	def _get_next(node):
		if not node.right:
			return node.parent
		n = node.right
		while n.left:
			n = n.left
		return n

class SegmentTree1:

	def __init__(self, data, default=2 ** 30, func=lambda a, b: min(a, b)):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class SegmentTree:

	def __init__(self, data, default=0, func=lambda a, b: a + b):
		self._default = default
		self._func = func
		self._len = len(data)
		self._size = _size = 1 << (self._len - 1).bit_length()
		self.data = [default] * (2 * _size)
		self.data[_size:_size + self._len] = data
		for i in reversed(range(_size)):
			self.data[i] = func(self.data[i + i], self.data[i + i + 1])

	def __delitem__(self, idx):
		self[idx] = self._default

	def __getitem__(self, idx):
		return self.data[idx + self._size]

	def __setitem__(self, idx, value):
		idx += self._size
		self.data[idx] = value
		idx >>= 1
		while idx:
			self.data[idx] = self._func(self.data[2 * idx], self.data[2 * idx + 1])
			idx >>= 1

	def __len__(self):
		return self._len

	def query(self, start, stop):
		if start == stop:
			return self.__getitem__(start)
		stop += 1
		start += self._size
		stop += self._size
		res = self._default
		while start < stop:
			if start & 1:
				res = self._func(res, self.data[start])
				start += 1
			if stop & 1:
				stop -= 1
				res = self._func(res, self.data[stop])
			start >>= 1
			stop >>= 1
		return res

	def __repr__(self):
		return 'SegmentTree({0})'.format(self.data)

class Factorial:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorials = [1, 1]
		self.invModulos = [0, 1]
		self.invFactorial_ = [1, 1]

	def calc(self, n):
		if n <= -1:
			print('Invalid argument to calculate n!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.factorials):
			return self.factorials[n]
		nextArr = [0] * (n + 1 - len(self.factorials))
		initialI = len(self.factorials)
		prev = self.factorials[-1]
		m = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * i % m
		self.factorials += nextArr
		return self.factorials[n]

	def inv(self, n):
		if n <= -1:
			print('Invalid argument to calculate n^(-1)')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		p = self.MOD
		pi = n % p
		if pi < len(self.invModulos):
			return self.invModulos[pi]
		nextArr = [0] * (n + 1 - len(self.invModulos))
		initialI = len(self.invModulos)
		for i in range(initialI, min(p, n + 1)):
			next = -self.invModulos[p % i] * (p // i) % p
			self.invModulos.append(next)
		return self.invModulos[pi]

	def invFactorial(self, n):
		if n <= -1:
			print('Invalid argument to calculate (n^(-1))!')
			print('n must be non-negative value. But the argument was ' + str(n))
			exit()
		if n < len(self.invFactorial_):
			return self.invFactorial_[n]
		self.inv(n)
		nextArr = [0] * (n + 1 - len(self.invFactorial_))
		initialI = len(self.invFactorial_)
		prev = self.invFactorial_[-1]
		p = self.MOD
		for i in range(initialI, n + 1):
			prev = nextArr[i - initialI] = prev * self.invModulos[i % p] % p
		self.invFactorial_ += nextArr
		return self.invFactorial_[n]

class Combination:

	def __init__(self, MOD):
		self.MOD = MOD
		self.factorial = Factorial(MOD)

	def ncr(self, n, k):
		if k < 0 or n < k:
			return 0
		k = min(k, n - k)
		f = self.factorial
		return f.calc(n) * f.invFactorial(max(n - k, k)) * f.invFactorial(min(k, n - k)) % self.MOD

def powm(a, n, m):
	if a == 1 or n == 0:
		return 1
	if n % 2 == 0:
		s = powm(a, n // 2, m)
		return s * s % m
	else:
		return a * powm(a, n - 1, m) % m

def sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z

def product(l):
	por = 1
	for i in range(len(l)):
		por *= l[i]
	return por

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] > k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

	def __init__(self):
		self.children = [None] * 26
		self.isEndOfWord = False

class Trie:

	def __init__(self):
		self.root = self.getNode()

	def getNode(self):
		return TrieNode()

	def _charToIndex(self, ch):
		return ord(ch) - ord('a')

	def insert(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				pCrawl.children[index] = self.getNode()
			pCrawl = pCrawl.children[index]
		pCrawl.isEndOfWord = True

	def search(self, key):
		pCrawl = self.root
		length = len(key)
		for level in range(length):
			index = self._charToIndex(key[level])
			if not pCrawl.children[index]:
				return False
			pCrawl = pCrawl.children[index]
		return pCrawl != None and pCrawl.isEndOfWord

def merge(arr, temp, left, mid, right):
	inv_count = 0
	i = left
	j = mid
	k = left
	while i <= mid - 1 and j <= right:
		if arr[i] <= arr[j]:
			temp[k] = arr[i]
			k += 1
			i += 1
		else:
			temp[k] = arr[j]
			k += 1
			j += 1
			inv_count = inv_count + (mid - i)
	while i <= mid - 1:
		temp[k] = arr[i]
		k += 1
		i += 1
	while j <= right:
		temp[k] = arr[j]
		k += 1
		j += 1
	for i in range(left, right + 1, 1):
		arr[i] = temp[i]
	return inv_count

def _mergeSort(arr, temp, left, right):
	inv_count = 0
	if right > left:
		mid = int((right + left) / 2)
		inv_count = _mergeSort(arr, temp, left, mid)
		inv_count += _mergeSort(arr, temp, mid + 1, right)
		inv_count += merge(arr, temp, left, mid + 1, right)
	return inv_count

def countSwaps(arr, n):
	temp = [0 for i in range(n)]
	return _mergeSort(arr, temp, 0, n - 1)

def minSwaps(arr):
	n = len(arr)
	arrpos = [*enumerate(arr)]
	arrpos.sort(key=lambda it: it[1])
	vis = {k: False for k in range(n)}
	ans = 0
	for i in range(n):
		if vis[i] or arrpos[i][0] == i:
			continue
		cycle_size = 0
		j = i
		while not vis[j]:
			vis[j] = True
			j = arrpos[j][0]
			cycle_size += 1
		if cycle_size > 0:
			ans += cycle_size - 1
	return ans

class Node:

	def __init__(self, data):
		self.data = data
		self.count = 0
		self.left = None
		self.right = None

class BinaryTrie:

	def __init__(self):
		self.root = Node(0)

	def insert(self, pre_xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = pre_xor & 1 << i
			if val:
				if not self.temp.right:
					self.temp.right = Node(0)
				self.temp = self.temp.right
				self.temp.count += 1
			if not val:
				if not self.temp.left:
					self.temp.left = Node(0)
				self.temp = self.temp.left
				self.temp.count += 1
		self.temp.data = pre_xor

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
(n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
pre = [0] * (n + 1)
for i in range(1, n + 1):
	pre[i] = pre[i - 1] + l[i - 1]

def find(x):
	for i in range(1, n + 1):
		tr = l[i - 1]
		req = tr * i - pre[i]
		ind = countGreater(l, n, tr + x)
		req += pre[n] - pre[n - ind] - (tr + x) * ind
		if req <= k:
			return True
		tr = l[i - 1]
		req = pre[n] - pre[i - 1] - tr * (n - i + 1)
		ind = binarySearchCount(l, n, tr - x)
		req += (tr - x) * ind - pre[ind]
		if req <= k:
			return True
	return False
st = 0
end = l[-1] - l[0]
ans = end
while st <= end:
	mid = (st + end) // 2
	if find(mid) == True:
		ans = mid
		end = mid - 1
	else:
		st = mid + 1
print(ans)


def main():
	(n, k) = readIntArr()
	a = readIntArr()
	a.sort()
	l = 0
	r = n - 1
	leftCnt = 1
	rightCnt = 1
	leftVal = a[0]
	rightVal = a[n - 1]
	while l < r:
		if leftCnt < rightCnt:
			if k >= leftCnt * (a[l + 1] - a[l]):
				k -= leftCnt * (a[l + 1] - a[l])
				leftCnt += 1
				leftVal = a[l + 1]
				l += 1
			else:
				lIncrement = k // leftCnt
				leftVal += lIncrement
				break
		elif k >= rightCnt * (a[r] - a[r - 1]):
			k -= rightCnt * (a[r] - a[r - 1])
			rightCnt += 1
			rightVal = a[r - 1]
			r -= 1
		else:
			rDecrement = k // rightCnt
			rightVal -= rDecrement
			break
	print(rightVal - leftVal)
	return
import sys
input = sys.stdin.buffer.readline

def oneLineArrayPrint(arr):
	print(' '.join([str(x) for x in arr]))

def multiLineArrayPrint(arr):
	print('\n'.join([str(x) for x in arr]))

def multiLineArrayOfArraysPrint(arr):
	print('\n'.join([' '.join([str(x) for x in y]) for y in arr]))

def readIntArr():
	return [int(x) for x in input().split()]

def makeArr(defaultVal, dimensionArr):
	dv = defaultVal
	da = dimensionArr
	if len(da) == 1:
		return [dv for _ in range(da[0])]
	else:
		return [makeArr(dv, da[1:]) for _ in range(da[0])]

def queryInteractive(x, y):
	print('? {} {}'.format(x, y))
	sys.stdout.flush()
	return int(input())

def answerInteractive(ans):
	print('! {}'.format(ans))
	sys.stdout.flush()
inf = float('inf')
MOD = 10 ** 9 + 7
for _abc in range(1):
	main()


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import bisect
(n, k) = map(int, input().split())
vals = list(map(int, input().split()))
vals.sort()
a1 = []
a2 = []
if n % 2 == 1:
	moves = 0
	for s in range(n // 2):
		moves += abs(vals[s + 1] - vals[s]) * (s + 1)
		moves += abs(vals[-1 - (s + 1)] - vals[-1 - s]) * (s + 1)
		a1.append(moves)
		a2.append(abs(vals[s + 1] - vals[-1 - (s + 1)]))
else:
	moves = 0
	for s in range(n // 2 - 1):
		moves += abs(vals[s + 1] - vals[s]) * (s + 1)
		moves += abs(vals[-1 - (s + 1)] - vals[-1 - s]) * (s + 1)
		a1.append(moves)
		a2.append(abs(vals[s + 1] - vals[-1 - (s + 1)]))
	moves += abs(vals[n // 2 - 1] - vals[n // 2]) * (n // 2)
	a1.append(moves)
	a2.append(0)
ind = bisect.bisect_left(a1, k)
if k < a1[0]:
	print(abs(vals[0] - vals[-1]) - k)
elif k >= a1[-1]:
	print(0)
elif k == a1[ind]:
	print(a2[ind])
elif k < a1[ind]:
	print(a2[ind - 1] - (k - a1[ind - 1]) // (ind + 1))


import sys

def minp():
	return sys.stdin.readline().strip()

def mint():
	return int(minp())

def mints():
	return map(int, minp().split())

def solve():
	(n, k) = mints()
	a = list(mints())
	a.sort()
	b = []
	c = []
	i = 0
	while i < n:
		j = i + 1
		while j < n and a[j] == a[i]:
			j += 1
		b.append(a[i])
		c.append(j - i)
		i = j
	l = 0
	r = len(b) - 1
	while l < r and k > 0:
		if c[l] < c[r]:
			x = min(b[l] + k // c[l], b[l + 1])
			k -= (x - b[l]) * c[l]
			if x == b[l + 1]:
				c[l + 1] += c[l]
				l += 1
			else:
				b[l] = x
				break
		else:
			x = max(b[r] - k // c[r], b[r - 1])
			k -= (b[r] - x) * c[r]
			if x == b[r - 1]:
				c[r - 1] += c[r]
				r -= 1
			else:
				b[r] = x
				break
	print(b[r] - b[l])
solve()


(n, k) = map(int, input().split())
a = sorted(map(int, input().split()))
(l, r) = (0, n - 1)
b = False
while r - l > 0 and k > 0:
	x = (a[l + 1] - a[l]) * (l + 1) + (a[r] - a[r - 1]) * (n - r)
	if x >= k:
		ans = max(a[r] - a[l] - k // (l + 1), 0)
		print(ans)
		b = True
	k -= x
	l += 1
	r -= 1
if b == False:
	print(0)


from sys import stdin
from collections import deque
(n, k) = [int(x) for x in stdin.readline().split()]
a = deque(sorted([int(x) for x in stdin.readline().split()]))
base = a[-1] - a[0]
group = 0
flag = False
while k and len(a) > 1:
	group += 1
	l = a[1] - a[0]
	r = a[-1] - a[-2]
	if k >= group * (l + r):
		k -= group * (l + r)
		a.pop()
		a.popleft()
	else:
		flag = True
		l = a[0]
		h = a[-1]
		print(h - l - k // group)
		k = 0
if not flag:
	print(0)


def solve(k, a):
	a.sort()
	ans = a[-1] - a[0]
	if ans == 0:
		return 0
	q1 = []
	q2 = []
	for i in range(1, len(a)):
		if a[i] != a[i - 1]:
			q1.append([i, a[i] - a[i - 1]])
	a = a[::-1]
	for i in range(1, len(a)):
		if a[i] != a[i - 1]:
			q2.append([i, a[i - 1] - a[i]])
	(i1, i2) = (0, 0)
	while k >= min(q1[i1][0], q2[i2][0]) and ans > 0:
		if q1[i1][0] <= q2[i2][0]:
			ansd = min(q1[i1][1], k // q1[i1][0])
			ans -= ansd
			k -= ansd * q1[i1][0]
			i1 += 1
		else:
			ansd = min(q2[i2][1], k // q2[i2][0])
			ans -= ansd
			k -= ansd * q2[i2][0]
			i2 += 1
		if max(i1, i2) >= len(q1):
			break
	return max(0, ans)

def main():
	(_, k) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	print(solve(k, a))
main()


(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort()
left = 1
right = 1
while 1:
	if left * (a[left] - a[left - 1]) <= k:
		k -= left * (a[left] - a[left - 1])
		left += 1
	else:
		print(a[n - right] - a[left - 1] - int(k / left))
		return
	if left + right > n:
		print(0)
		return
	if right * (a[n - right] - a[n - 1 - right]) <= k:
		k -= right * (a[n - right] - a[n - 1 - right])
		right += 1
	else:
		print(a[n - right] - a[left - 1] - int(k / right))
		return
	if left + right > n:
		print(0)
		return


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
a.append(-1)
count = 1
b = []
add = 0
for i in range(n):
	if a[i] == a[i + 1]:
		count += 1
	else:
		b.append([a[i], count])
		count = 1
		add += 1
i = 0
j = add - 1
(e, f) = (b[i][1], b[j][1])
plus = 0
flag = 0
while i < j:
	if e <= f and (b[i + 1][0] - b[i][0]) * e <= k:
		k -= (b[i + 1][0] - b[i][0]) * e
		e += b[i + 1][1]
		i += 1
	elif f < e and (b[j][0] - b[j - 1][0]) * f <= k:
		k -= (b[j][0] - b[j - 1][0]) * f
		f += b[j - 1][1]
		j -= 1
	elif e <= f and (b[i + 1][0] - b[i][0]) * e > k:
		i = b[i][0] + k // e
		flag = 1
		break
	elif f < e and (b[j][0] - b[j - 1][0]) * f > k:
		j = b[j][0] - k // f
		flag = 2
		break
if flag == 1:
	print(b[j][0] - i)
elif flag == 2:
	print(j - b[i][0])
else:
	print(b[j][0] - b[i][0])


import os, sys
from io import BytesIO, IOBase
from bisect import bisect_left, bisect_right

def check(mid, a, n, k, pref):
	for i in range(n):
		r = a[i] * (i + 1) - pref[i + 1]
		y = bisect_left(a, a[i] + mid)
		r += pref[-1] - pref[y] - (a[i] + mid) * (n - y)
		if r <= k:
			return 1
		r = pref[-1] - pref[i] - (n - i) * a[i]
		y = bisect_right(a, a[i] - mid) - 1
		r += (a[i] - mid) * (y + 1) - pref[y + 1]
		if r <= k:
			return 1
	return 0

def main():
	(n, k) = map(int, input().split())
	a = sorted(map(int, input().split()))
	pref = [0]
	for i in range(n):
		pref.append(pref[-1] + a[i])
	(hi, lo, ans) = (10 ** 9, 0, 10 ** 9)
	while hi >= lo:
		mid = (hi + lo) // 2
		if check(mid, a, n, k, pref):
			ans = mid
			hi = mid - 1
		else:
			lo = mid + 1
	print(ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()


(n, k) = map(int, input().split())
l1 = list(map(int, input().split()))
l1.sort()
i = 0
j = n - 1
left = 1
right = 1
while i < j and k > 0:
	x = l1[i + 1] - l1[i]
	y = l1[j] - l1[j - 1]
	if left == right:
		if k >= left * x:
			k -= left * x
			i += 1
			left += 1
		else:
			l1[i] += k // left
			break
	elif k >= right * y:
		k -= right * y
		j -= 1
		right += 1
	else:
		l1[j] -= k // right
		break
print(l1[j] - l1[i])


import sys
from bisect import bisect_left, bisect_right
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
i = 0
j = n - 1
res = a[j] - a[i]
while res > 0:
	if i == j - 1:
		used = (a[i + 1] - a[i]) * (i + 1)
	else:
		used = (a[i + 1] - a[i] + a[j] - a[j - 1]) * (i + 1)
	if used >= k:
		res -= k // (i + 1)
		break
	k -= used
	if i == j - 1:
		res = 0
		break
	res = a[j - 1] - a[i + 1]
	j -= 1
	i += 1
print(res)


class Solve:

	def __init__(self):
		(self.n, self.k) = map(int, input().split())
		self.fuad = list(map(int, input().split()))
		self.fuad.sort()

	def FuckCase(self):
		for i in range(int(self.n / 2)):
			s = (self.fuad[i + 1] - self.fuad[i]) * (i + 1) + (self.fuad[self.n - i - 1] - self.fuad[self.n - i - 2]) * (i + 1)
			if s <= self.k:
				self.k -= s
			else:
				print(self.fuad[self.n - i - 1] - self.fuad[i] - int(self.k / (i + 1)))
				return
		print('0')
obj = Solve()
obj.FuckCase()


import sys
from collections import Counter
input = sys.stdin.readline
(n, k) = list(map(int, input().split()))
A = list(map(int, input().split()))
S = sorted(set(A))
if len(S) == 1:
	print(0)
	return
MIN0 = 0
MIN1 = 1
MAX0 = -1
MAX1 = -2
C = Counter(A)
while k and S[MIN0] != S[MAX0]:
	if C[S[MIN0]] <= C[S[MAX0]] and k >= C[S[MIN0]]:
		if k >= (S[MIN1] - S[MIN0]) * C[S[MIN0]]:
			k -= (S[MIN1] - S[MIN0]) * C[S[MIN0]]
			C[S[MIN1]] += C[S[MIN0]]
			del C[S[MIN0]]
			MIN0 += 1
			MIN1 += 1
		else:
			print(S[MAX0] - (S[MIN0] + k // C[S[MIN0]]))
			return
	elif C[S[MAX0]] <= C[S[MIN0]] and k >= C[S[MAX0]]:
		if k >= (S[MAX0] - S[MAX1]) * C[S[MAX0]]:
			k -= (S[MAX0] - S[MAX1]) * C[S[MAX0]]
			C[S[MAX1]] += C[S[MAX0]]
			del C[S[MAX0]]
			MAX0 -= 1
			MAX1 -= 1
		else:
			print(S[MAX0] - k // C[S[MAX0]] - S[MIN0])
			return
	else:
		break
print(S[MAX0] - S[MIN0])


(n, k) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
(i, j) = (0, n - 1)
(cnt0, cnt1) = (1, 1)
(left, right) = (l[0], l[-1])
while i < j:
	if cnt0 < cnt1:
		x = l[i + 1] - l[i]
		if cnt0 * x <= k:
			k -= cnt0 * x
			cnt0 += 1
			i += 1
			left = l[i]
		else:
			num = k // cnt0
			left = l[i] + num
			break
	else:
		x = l[j] - l[j - 1]
		if cnt1 * x <= k:
			k -= cnt1 * x
			cnt1 += 1
			j -= 1
			right = l[j]
		else:
			num = k // cnt1
			right = l[j] - num
			break
print(right - left)


(n, k) = [int(x) for x in input().split()]
d = {}
b = []
for i in map(int, input().split()):
	if i not in d:
		b.append(i)
		d[i] = 1
	else:
		d[i] += 1
b.sort()
(mi, ma) = (0, len(b) - 1)
(left, right) = (b[mi], b[ma])
(am_left, am_right) = (d[b[mi]], d[b[ma]])
(mi, ma) = (1, len(b) - 2)
while right - left > 0:
	if am_left <= am_right:
		if (b[mi] - left) * am_left <= k:
			k -= (b[mi] - left) * am_left
			left = b[mi]
			am_left += d[b[mi]]
			mi += 1
		else:
			left += k // am_left
			break
	elif (right - b[ma]) * am_right <= k:
		k -= (right - b[ma]) * am_right
		right = b[ma]
		am_right += d[b[ma]]
		ma -= 1
	else:
		right -= k // am_right
		break
print(right - left)


from sys import stdin
(n, k) = [int(i) for i in stdin.readline().strip().split()]
a = [int(i) for i in stdin.readline().strip().split()]
a.sort()
ups = n * [0]
downs = n * [0]
for i in range(0, n - 1):
	ups[i + 1] = ups[i] + (i + 1) * (a[i + 1] - a[i])
for i in range(n - 1, 0, -1):
	downs[i - 1] = downs[i] + (n - i) * (a[i] - a[i - 1])

def find_max(steps):
	(l, r) = (0, n - 1)
	x = None
	while l <= r:
		m = (l + r) // 2
		if downs[m] <= steps:
			x = m
			r = m - 1
		else:
			l = m + 1
	value = a[x]
	if x > 0 and downs[x] < steps:
		value -= (steps - downs[x]) // (n - x)
	return value

def find_min(steps):
	(l, r) = (0, n - 1)
	x = None
	while l <= r:
		m = (l + r) // 2
		if ups[m] <= steps:
			x = m
			l = m + 1
		else:
			r = m - 1
	value = a[x]
	if x < n:
		value += (steps - ups[x]) // (x + 1)
	return value
best_diff = a[-1] - a[0]
for i in range(n):
	if ups[i] > k:
		break
	min_a = a[i]
	max_a = find_max(k - ups[i])
	if max_a <= min_a:
		best_diff = 0
		break
	best_diff = min(best_diff, max_a - min_a)
for i in range(n - 1, -1, -1):
	if best_diff == 0:
		break
	if downs[i] > k:
		break
	max_a = a[i]
	min_a = find_min(k - downs[i])
	if min_a >= max_a:
		best_diff = 0
		break
	best_diff = min(best_diff, max_a - min_a)
print(best_diff)


(n, k) = list(map(int, input().split()))
a = sorted(map(int, input().split()))
i = 1
while True:
	ans = a[-i] - a[i - 1]
	if (a[i] - a[i - 1]) * i >= k:
		ans -= k // i
		break
	ans = a[-i] - a[i]
	k += a[i - 1] * i
	k -= a[i] * i
	if (a[-i] - a[-i - 1]) * i >= k:
		ans -= k // i
		break
	k += a[-i - 1] * i
	k -= a[-i] * i
	i += 1
	if not ans:
		break
print(ans)


from sys import stdin
(n, k) = [int(i) for i in stdin.readline().strip().split()]
a = [int(i) for i in stdin.readline().strip().split()]
a.sort()
i = 0
j = n - 1
a_min = a[i]
a_max = a[j]
while i < j:
	if a[i] == a[i + 1]:
		i += 1
		a_min = a[i]
	elif a[j] == a[j - 1]:
		j -= 1
		a_max = a[j]
	elif i + 1 <= n - j:
		required_steps = (a[i + 1] - a[i]) * (i + 1)
		if required_steps > k:
			a_min += k // (i + 1)
			break
		else:
			i += 1
			k -= required_steps
			a_min = a[i]
	else:
		required_steps = (a[j] - a[j - 1]) * (n - j)
		if required_steps > k:
			a_max -= k // (n - j)
			break
		else:
			j -= 1
			k -= required_steps
			a_max = a[j]
print(a_max - a_min)


from collections import defaultdict
from itertools import accumulate
from bisect import bisect_left
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
d = defaultdict(int)
for u in a:
	d[u] += 1
c = sorted(d.keys())
cnt = [d[i] for i in c]
snt = [i * d[i] for i in c]
pc = list(accumulate(cnt))
sc = list(accumulate(cnt[::-1]))[::-1]
ps = list(accumulate(snt))
ss = list(accumulate(snt[::-1]))[::-1]

def get_high(rest):
	(l, r) = (c[0] - 1, c[-1])
	while r - l > 1:
		mid = (l + r) // 2 + (l + r) % 2
		i = bisect_left(c, mid)
		if ss[i] - mid * sc[i] <= rest:
			r = mid
		else:
			l = mid
	return r

def calc_ans(low):
	if low < c[0]:
		return 10 ** 100
	i = bisect_left(c, low)
	if c[i] != low:
		i -= 1
	if low * pc[i] - ps[i] > k:
		return 10 ** 100
	rest = k - (low * pc[i] - ps[i])
	high = get_high(rest)
	return max(high - low, 0)
(l, r) = (c[0], c[-1])
while r - l > 1:
	mid = (l + r) // 2
	mm = (mid + r) // 2
	if calc_ans(mid) <= calc_ans(mm):
		r = mm
	else:
		l = mid
print(min(calc_ans(l), calc_ans(r)))


import sys
import math
(n, k) = map(int, input().split())
A = [int(i) for i in input().split()]
A.sort()
l = 0
r = n - 1
while l < r and k:
	temp = (A[l + 1] - A[l]) * (l + 1) + (A[r] - A[r - 1]) * (n - r)
	if k >= temp:
		k -= temp
		l += 1
		r -= 1
	else:
		ans = A[r] - A[l] - k // (l + 1)
		print(ans)
		sys.exit(0)
print(0)


(n, k) = [int(i) for i in input().split()]
d = [int(i) for i in input().split()]
mn = min(d)
mx = max(d)
dic = {}
for dd in d:
	if dd in dic:
		dic[dd] += 1
	else:
		dic[dd] = 1
ans = 0
vals = list(dic.keys())
vals.sort()
loi = 0
hii = len(vals) - 1
while loi < hii:
	locl = vals[loi]
	hicl = vals[hii]
	lowidth = dic[locl]
	hiwidth = dic[hicl]
	if lowidth < hiwidth:
		lonl = vals[loi + 1]
		delta = lonl - locl
		mxdelta = k // lowidth
		if mxdelta <= delta:
			ans = hicl - (locl + mxdelta)
			break
		else:
			dic[lonl] += dic[locl]
			del dic[locl]
			k -= lowidth * delta
			loi += 1
	else:
		hinl = vals[hii - 1]
		delta = hicl - hinl
		mxdelta = k // hiwidth
		if mxdelta <= delta:
			ans = hicl - mxdelta - locl
			break
		else:
			dic[hinl] += dic[hicl]
			del dic[hicl]
			k -= hiwidth * delta
			hii -= 1
print(ans)


import sys
input = sys.stdin.readline
import collections
from collections import defaultdict
(n, k) = map(int, input().split())
l = [int(i) for i in input().split()]
l.sort()
freq = defaultdict(list)
for i in l:
	if i not in freq:
		freq[i].append(1)
	else:
		freq[i][0] += 1
l = list(set(l))
l.sort()
count = 0
beg = 0
last = len(l) - 1
diff = l[last] - l[beg]
while count < k and diff > 0:
	if freq[l[beg]] < freq[l[last]]:
		if count + freq[l[beg]][0] <= k and diff >= 0:
			diff -= min((k - count) // freq[l[beg]][0], l[beg + 1] - l[beg])
			count += min(k - count, freq[l[beg]][0] * (l[beg + 1] - l[beg]))
			freq[l[beg + 1]][0] += freq[l[beg]][0]
			beg += 1
		else:
			count = k
	elif count + freq[l[last]][0] <= k and diff >= 0:
		diff -= min((k - count) // freq[l[last]][0], l[last] - l[last - 1])
		count += min(k - count, freq[l[last]][0] * (l[last] - l[last - 1]))
		freq[l[last - 1]][0] += freq[l[last]][0]
		last -= 1
	else:
		count = k
print(diff)


(n, k) = list(map(int, input().split()))
l = list(map(int, input().split()))
l.sort()
s = 0
for i in range(n):
	s += abs(l[i] - l[n // 2])
if s <= k:
	print(0)
else:
	i = 0
	while True:
		if i == n - 1:
			break
		if l[i + 1] != l[i]:
			break
		i += 1
	p = i
	left = p + 1
	i = n - 1
	while True:
		if i == 0:
			break
		if l[i - 1] != l[i]:
			break
		i -= 1
	kon = i
	right = n - kon
	while True:
		if left <= right:
			if k >= left * (l[p + 1] - l[p]):
				k -= left * (l[p + 1] - l[p])
				while True:
					p += 1
					left += 1
					if p >= n:
						break
					if l[p + 1] != l[p]:
						break
			else:
				print(l[kon] - l[p] - k // left)
				break
		elif k >= right * (l[kon] - l[kon - 1]):
			k -= right * (l[kon] - l[kon - 1])
			while True:
				kon -= 1
				right += 1
				if kon == 0:
					break
				if l[kon] != l[kon - 1]:
					break
		else:
			print(l[kon] - l[p] - k // right)
			break


(n, k) = [int(i) for i in input().split(' ')]
a = sorted([int(i) for i in input().split(' ')])
if n == 1:
	print(0)
	exit()
tot = 0
(i, j) = (1, n - 2)
while j - i >= -1:
	do = i > n - j - 1
	last = tot
	tot += i * (a[i] - a[i - 1]) if not do else (n - j - 1) * (a[j + 1] - a[j])
	if tot >= k:
		if do:
			a[-1] -= (k - last) // (n - j - 1)
		else:
			a[0] += (k - last) // i
		break
	if do:
		a[-1] = a[j]
		j -= 1
	else:
		a[0] = a[i]
		i += 1
print(a[-1] - a[0])


(n, k) = list(map(int, input().split()))
li = list(map(int, input().split()))
d = {}
l = []
for i in li:
	try:
		d[i] += 1
	except KeyError:
		d[i] = 1
		l.append(i)
l.sort()
z = 1
a = 0
b = len(l) - 1
while k > 0:
	if a == b:
		z = 0
		break
	if d[l[a]] > d[l[b]]:
		s = d[l[b]] * (l[b] - l[b - 1])
		if s <= k:
			k -= s
			d[l[b - 1]] += d[l[b]]
			b -= 1
		else:
			b1 = k // d[l[b]]
			z = 2
			break
	else:
		s = d[l[a]] * (l[a + 1] - l[a])
		if s <= k:
			k -= s
			d[l[a + 1]] += d[l[a]]
			a += 1
		else:
			a1 = k // d[l[a]]
			z = 3
			break
if z == 0:
	print(0)
elif z == 1:
	print(l[b] - l[a])
elif z == 2:
	print(l[b] - l[a] - b1)
else:
	print(l[b] - l[a] - a1)


from sys import stdin
input = iter(stdin.buffer.read().decode().splitlines()).__next__
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
left = 1
right = 1
while 1:
	if left * (a[left] - a[left - 1]) <= k:
		k -= left * (a[left] - a[left - 1])
		left += 1
	else:
		print(a[n - right] - a[left - 1] - int(k / left))
		exit()
	if left + right > n:
		print(0)
		exit()
	if right * (a[n - right] - a[n - 1 - right]) <= k:
		k -= right * (a[n - right] - a[n - 1 - right])
		right += 1
	else:
		print(a[n - right] - a[left - 1] - int(k / right))
		exit()
	if left + right > n:
		print(0)
		exit()


from sys import stdin, stdout

def getmindifference(n, k, a):
	a.sort()
	lcnt = 1
	rcnt = 1
	lmin = a[0]
	rmax = a[len(a) - 1]
	lidx = 0
	ridx = len(a) - 1
	while k > 0 and lidx < ridx:
		if lcnt <= rcnt:
			needk = min(k, (a[lidx + 1] - a[lidx]) * lcnt)
			lmin += needk // lcnt
			lcnt += 1
			lidx += 1
			k -= needk
		else:
			needk = min(k, (a[ridx] - a[ridx - 1]) * rcnt)
			rmax -= needk // rcnt
			rcnt += 1
			ridx -= 1
			k -= needk
	res = rmax - lmin
	if res < 0:
		res = 0
	return res
nk = list(map(int, stdin.readline().split()))
n = nk[0]
k = nk[1]
a = list(map(int, stdin.readline().split()))
res = getmindifference(n, k, a)
stdout.write(str(res))


(n, k) = map(int, input().split())
a = [int(x) for x in input().split()]
a.sort()
L1 = []
L2 = []
for i in range(0, n - 1):
	L1.append(a[i + 1] - a[i])
for i in range(len(a) - 1, 0, -1):
	L2.append(a[i] - a[i - 1])
L2 = L2 + [0]
L2 = L2[::-1]
L1 = L1 + [0]
low = 0
high = len(a) - 1
c1 = 1
c2 = 1
while low < high:
	mn = 0
	temp = 0
	if 1 / c1 >= 1 / c2:
		mn = c1 * L1[low]
		if mn <= k:
			temp = 1
			k -= mn
			c1 += 1
			low += 1
	else:
		mn = c2 * L2[high]
		if mn <= k:
			temp = 1
			k -= mn
			c2 += 1
			high -= 1
	if temp == 0:
		break
	if k <= 0:
		break
if low >= high:
	print(0)
else:
	ans = a[high] - a[low]
	if c1 <= c2:
		t = k // c1
		ans -= t
	else:
		t = k // c2
		ans -= t
	print(ans)


(n, k) = map(int, input().split())
b = list(map(int, input().split()))
a = []
dic = {}
for i in b:
	try:
		if dic[i]:
			dic[i] += 1
	except KeyError:
		dic[i] = 1
		a.append(i)
a.sort()
i = 0
j = len(a) - 1
while 1:
	frst = a[i]
	last = a[j]
	if frst == last:
		break
	fcost = dic[frst]
	lcost = dic[last]
	fnxt = a[i + 1]
	lnxt = a[j - 1]
	fnxtcost = fnxt - frst
	lnxtcost = last - lnxt
	ftotal = fcost * fnxtcost
	ltotal = lcost * lnxtcost
	if fcost <= lcost:
		if ftotal <= k:
			i += 1
			k -= ftotal
			dic[fnxt] += fcost
			dic[frst] = 0
		else:
			temp = k // fcost
			frst += temp
			k -= k * temp
			break
	elif ltotal <= k:
		j -= 1
		k -= ltotal
		dic[lnxt] += lcost
		dic[last] = 0
	else:
		temp = k // lcost
		k -= k * temp
		last -= temp
		break
print(last - frst)


import atexit
import io
import sys
_INPUT_LINES = sys.stdin.read().splitlines()
input = iter(_INPUT_LINES).__next__
_OUTPUT_BUFFER = io.StringIO()
sys.stdout = _OUTPUT_BUFFER

@atexit.register
def write():
	sys.__stdout__.write(_OUTPUT_BUFFER.getvalue())
(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort()
left = 1
right = 1
while 1:
	if left * (a[left] - a[left - 1]) <= k:
		k -= left * (a[left] - a[left - 1])
		left += 1
	else:
		print(a[n - right] - a[left - 1] - int(k / left))
		return
	if left + right > n:
		print(0)
		return
	if right * (a[n - right] - a[n - 1 - right]) <= k:
		k -= right * (a[n - right] - a[n - 1 - right])
		right += 1
	else:
		print(a[n - right] - a[left - 1] - int(k / right))
		return
	if left + right > n:
		print(0)
		return


import sys
import math
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
start = 0
end = n - 1
n_operations = 0
min_i = 0
max_i = n - 1
while True:
	d = a[end] - a[start]
	if min_i > max_i or n_operations >= k:
		break
	for i in range(start, end + 1):
		if a[i] != a[start]:
			min_i = i
			break
	if min_i == start:
		print(0)
		exit()
	for i in reversed(range(start, end + 1)):
		if a[i] != a[end]:
			max_i = i
			break
	cur_operations = 0
	if min_i <= n - 1 - max_i:
		cur_operations = (a[min_i] - a[start]) * min_i
		start = min_i
	else:
		cur_operations = (a[end] - a[max_i]) * (n - 1 - max_i)
		end = max_i
	if n_operations + cur_operations > k:
		d = d - int((k - n_operations) / min(min_i, n - 1 - max_i))
		break
	n_operations += cur_operations
print(d)


(n, k) = map(int, input().split())
a = input().split()
for i in range(n):
	a[i] = int(a[i])
a.sort()
b = []
count = 0
for i in range(n):
	if i == 0:
		count += 1
		if i == n - 1:
			b.append([a[i], count])
	elif a[i] == a[i - 1]:
		count += 1
		if i == n - 1:
			b.append([a[i], count])
	else:
		b.append([a[i - 1], count])
		count = 1
		if i == n - 1:
			b.append([a[i], count])
while k:
	if len(b) == 1:
		break
	if b[0][1] < b[len(b) - 1][1]:
		if k >= (b[1][0] - b[0][0]) * b[0][1]:
			b[1][1] += b[0][1]
			k -= (b[1][0] - b[0][0]) * b[0][1]
			b.pop(0)
		else:
			b[0][0] += k // b[0][1]
			k = 0
	elif k >= (b[len(b) - 1][0] - b[len(b) - 2][0]) * b[len(b) - 1][1]:
		b[len(b) - 2][1] += b[len(b) - 1][1]
		k -= (b[len(b) - 1][0] - b[len(b) - 2][0]) * b[len(b) - 1][1]
		b.pop(len(b) - 1)
	else:
		b[len(b) - 1][0] -= k // b[len(b) - 1][1]
		k = 0
print(b[len(b) - 1][0] - b[0][0])


import math
(n, k) = tuple(map(int, input().split()))
nums = sorted(list(map(int, input().split())))
l = 0
r = n - 1
while l < r:
	x = (nums[l + 1] - nums[l]) * (l + 1) + (nums[r] - nums[r - 1]) * (n - r)
	if x >= k:
		ans = max(nums[r] - nums[l] - math.floor(k / (l + 1)), 0)
		print(ans)
		exit(0)
	l += 1
	r -= 1
	k -= x
print(0)


import sys, math
input = sys.stdin.readline
(n, k) = map(int, input().split())
a = list(map(int, input().split()))
a.sort()
i = 1
while i > 0:
	q = a[-i] - a[i - 1]
	if (a[i] - a[i - 1]) * i >= k:
		q = q - k // i
		break
	k = k + a[i - 1] * i - a[i] * i
	q = a[-i] - a[i]
	if (a[-i] - a[-i - 1]) * i >= k:
		q = q - k // i
		break
	k = k + a[-i - 1] * i - a[-i] * i
	i = i + 1
	if not q:
		break
print(q)


(n, k) = map(int, input().split())
seq = list(sorted(map(int, input().split())))
i = 0
j = n - 1
result = seq[n - 1] - seq[0]
while result > 0:
	if i == j - 1:
		used = (seq[i + 1] - seq[i]) * (i + 1)
	else:
		used = (seq[i + 1] - seq[i] + seq[j] - seq[j - 1]) * (i + 1)
	if used >= k:
		result -= k // (i + 1)
		break
	k -= used
	if i == j - 1:
		result = 0
		break
	result = seq[j - 1] - seq[i + 1]
	i += 1
	j -= 1
print(result)


(g, f) = map(int, input().split())
a = sorted(map(int, input().split()))
(l, j) = (0, g - 1)
b = False
while j - l > 0 and f > 0:
	x = (a[l + 1] - a[l]) * (l + 1) + (a[j] - a[j - 1]) * (g - j)
	if x >= f:
		ans = max(a[j] - a[l] - f // (l + 1), 0)
		print(ans)
		b = True
	f -= x
	l += 1
	j -= 1
if b == False:
	print(0)


(n, k) = map(int, input().split())
a = list(map(int, input().split()))
cnt = {}
for elem in a:
	if elem in cnt:
		cnt[elem] += 1
	else:
		cnt[elem] = 1
cnt = sorted(list(cnt.items()))
for i in range(len(cnt)):
	cnt[i] = list(cnt[i])
left = 0
right = len(cnt) - 1
while k > 0:
	if k < cnt[left][1] and k < cnt[right][1]:
		break
	if left == right:
		break
	if cnt[left][1] <= cnt[right][1]:
		if k >= cnt[left][1] * (cnt[left + 1][0] - cnt[left][0]):
			k -= cnt[left][1] * (cnt[left + 1][0] - cnt[left][0])
			cnt[left + 1][1] += cnt[left][1]
			left += 1
		else:
			cnt[left][0] += k // cnt[left][1]
			k = 0
	elif k >= cnt[right][1] * (cnt[right][0] - cnt[right - 1][0]):
		k -= cnt[right][1] * (cnt[right][0] - cnt[right - 1][0])
		cnt[right - 1][1] += cnt[right][1]
		right -= 1
	else:
		cnt[right][0] -= k // cnt[right][1]
		k = 0
print(cnt[right][0] - cnt[left][0])


(n, k) = list(map(int, input().split()))
a = list(map(int, input().split()))
a.sort()
i = 0
j = n - 1
while i < j and k != 0:
	if i + 1 <= n - j:
		delta = a[i + 1] - a[i]
		if k >= (i + 1) * delta:
			up = delta
			k -= up * (i + 1)
			i += 1
		else:
			up = k // (i + 1)
			a[i] += up
			k = 0
	else:
		delta = abs(a[j] - a[j - 1])
		if k >= (n - j) * delta:
			down = delta
			k -= down * (n - j)
			j -= 1
		else:
			down = k // (n - j)
			a[j] -= down
			k = 0
print(a[j] - a[i])


from collections import deque
(n, k) = list(map(int, input().split()))
li = list(map(int, input().split()))
li.sort()
dq = deque()
a = li[0]
countt = 1
distp = -1
for i in range(1, len(li)):
	if li[i] == a:
		countt += 1
	else:
		dq.append([a, countt, distp, li[i] - a])
		distp = li[i] - a
		countt = 1
	a = li[i]
dq.append([a, countt, distp, -1])
diff = li[-1] - li[0]
while k > 0 and diff > 0:
	if dq[0][1] > dq[-1][1]:
		if k > dq[-1][2] * dq[-1][1]:
			k -= dq[-1][2] * dq[-1][1]
			x1 = dq.pop()
			x2 = dq.pop()
			dq.append([x2[0], x2[1] + x1[1], x2[2], -1])
			diff -= x1[0] - x2[0]
		else:
			diff -= k // dq[-1][1]
			k = 0
	elif k > dq[0][3] * dq[0][1]:
		k -= dq[0][3] * dq[0][1]
		x1 = dq.popleft()
		x2 = dq.popleft()
		dq.appendleft([x2[0], x2[1] + x1[1], -1, x2[3]])
		diff -= x2[0] - x1[0]
	else:
		diff -= k // dq[0][1]
		k = 0
print(diff)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from math import factorial
from collections import Counter, defaultdict, deque
from heapq import heapify, heappop, heappush

def RL():
	return map(int, sys.stdin.readline().rstrip().split())

def RLL():
	return list(map(int, sys.stdin.readline().rstrip().split()))

def N():
	return int(input())

def comb(n, m):
	return factorial(n) / (factorial(m) * factorial(n - m)) if n >= m else 0

def perm(n, m):
	return factorial(n) // factorial(n - m) if n >= m else 0

def mdis(x1, y1, x2, y2):
	return abs(x1 - x2) + abs(y1 - y2)
mod = 998244353
INF = float('inf')

def main():
	(n, k) = RL()
	arr = RLL()
	sarr = [(i, v) for (i, v) in Counter(arr).items()]
	sarr.sort()
	if len(sarr) == 1:
		print(0)
	else:
		tk = k
		(l, r) = (0, len(sarr) - 1)
		(ln, rn) = (0, 0)
		(lnum, rnum) = (sarr[l][0], sarr[r][0])
		res = rnum - lnum
		while l < r:
			(laddn, raddn) = (sarr[l + 1][0] - sarr[l][0], sarr[r][0] - sarr[r - 1][0])
			lc = (sarr[l][1] + ln) * laddn
			rc = (sarr[r][1] + rn) * raddn
			(pl, pr) = (sarr[l][1] + ln, sarr[r][1] + rn)
			if lc > tk:
				lc = tk
				laddn = tk // (sarr[l][1] + ln)
			if rc > tk:
				rc = tk
				raddn = tk // (sarr[r][1] + rn)
			if pl < pr:
				tk -= lc
				lnum += laddn
				if lnum == sarr[l + 1][0]:
					ln += sarr[l][1]
					l += 1
			else:
				tk -= rc
				rnum -= raddn
				if rnum == sarr[r - 1][0]:
					rn += sarr[r][1]
					r -= 1
			if tk >= 0:
				res = min(res, max(rnum - lnum, 0))
			if tk <= 0:
				break
		print(res)
main()


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from functools import cmp_to_key
from heapq import *
from math import gcd, factorial, floor, ceil, sqrt
from copy import deepcopy
from collections import deque
from bisect import bisect_left as bl
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = BytesIO()
		self.writable = 'x' in file.mode or 'r' not in file.mode
		self.write = self.buffer.write if self.writable else None

	def read(self):
		while True:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			if not b:
				break
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines = 0
		return self.buffer.read()

	def readline(self):
		while self.newlines == 0:
			b = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
			self.newlines = b.count(b'\n') + (not b)
			ptr = self.buffer.tell()
			(self.buffer.seek(0, 2), self.buffer.write(b), self.buffer.seek(ptr))
		self.newlines -= 1
		return self.buffer.readline()

	def flush(self):
		if self.writable:
			os.write(self._fd, self.buffer.getvalue())
			(self.buffer.truncate(0), self.buffer.seek(0))

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
from types import GeneratorType

def iterative(f, stack=[]):

	def wrapped_func(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		to = f(*args, **kwargs)
		while True:
			if type(to) is GeneratorType:
				stack.append(to)
				to = next(to)
				continue
			stack.pop()
			if not stack:
				break
			to = stack[-1].send(to)
		return to
	return wrapped_func

def inp():
	return sys.stdin.readline().rstrip('\r\n')

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

def stringlis():
	return list(map(str, inp().split()))

def sep():
	return map(int, inp().split())

def strsep():
	return map(str, inp().split())

def zerolist(n):
	return [0] * n

def nextline():
	out('\n')

def testcase(t):
	for pp in range(t):
		solve(pp)

def printlist(a):
	for p in range(0, len(a)):
		out(str(a[p]) + ' ')

def google(p):
	print('Case #' + str(p) + ': ', end='')

def lcm(a, b):
	return a * b // gcd(a, b)

def power(x, y, p):
	y %= p - 1
	res = 1
	x = x % p
	if x == 0:
		return 0
	while y > 0:
		if y & 1 == 1:
			res = res * x % p
		y = y >> 1
		x = x * x % p
	return res

def ncr(n, r):
	return factorial(n) // (factorial(r) * factorial(max(n - r, 1)))

def isPrime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	i = 5
	while i * i <= n:
		if n % i == 0 or n % (i + 2) == 0:
			return False
		i = i + 6
	return True
inf = pow(10, 20)
mod = 10 ** 9 + 7

def solve(case):
	(n, k) = sep()
	a = lis()
	a = sorted(a)
	pre = [0] * n
	for i in range(1, n):
		pre[i] = (a[i] - a[i - 1]) * i + pre[i - 1]
	suff = [0] * n
	for i in range(n - 2, -1, -1):
		suff[i] = (a[i + 1] - a[i]) * (n - i - 1) + suff[i + 1]
	ans = inf
	for i in range(n):
		if pre[i] > k:
			continue
		rem = k - pre[i]
		lo = 0
		hi = n - 1
		ind = n - 1
		while lo <= hi:
			mid = (lo + hi) // 2
			if suff[mid] <= rem:
				ind = min(ind, mid)
				hi = mid - 1
			else:
				lo = mid + 1
		if ind <= i:
			ans = 0
		else:
			rem -= suff[ind]
			ex = rem // (n - ind)
			ans = min(ans, a[ind] - a[i] - ex)
	for i in range(n - 1, -1, -1):
		if suff[i] > k:
			continue
		rem = k - suff[i]
		lo = 0
		hi = n - 1
		ind = 0
		while lo <= hi:
			mid = (lo + hi) // 2
			if pre[mid] <= rem:
				ind = max(ind, mid)
				lo = mid + 1
			else:
				hi = mid - 1
		if ind >= i:
			ans = 0
		else:
			rem -= pre[ind]
			ex = rem // (ind + 1)
			ans = min(ans, a[i] - a[ind] - ex)
	print(ans)
testcase(1)


import math
import sys
N = map
V = int
a = input
u = print
K = sys.exit
(n, k) = N(V, a().split())
A = [V(i) for i in a().split()]
A.sort()
l = 0
r = n - 1
while l < r and k:
	F = (A[l + 1] - A[l]) * (l + 1) + (A[r] - A[r - 1]) * (n - r)
	if k >= F:
		k -= F
		l += 1
		r -= 1
	else:
		f = A[r] - A[l] - k // (l + 1)
		u(f)
		K(0)
u(0)


(n, k) = map(int, input().split())
a = sorted(list(map(int, input().split())))
c = [a[i] for i in range(n)]
for i in range(1, n):
	c[i] += c[i - 1]
c.append(0)
(lnum, rnum) = (0, 0)
left = 0
right = n - 1
for i in range(n // 2 + n % 2):
	left = i
	lnum = i * a[i] - c[i - 1]
	if lnum + rnum >= k:
		break
	right = n - 1 - i
	rnum = c[n - 1] - c[n - 1 - i] - i * a[n - 1 - i]
	if lnum + rnum >= k:
		break
diff = a[right] - a[left]
d = lnum + rnum - k
if n % 2 == 0 and lnum + rnum < k:
	i = n // 2
	num = i * a[i] - c[i - 1]
	i -= 1
	num += c[n - 1] - c[n - 1 - i] - i * a[n - 1 - i]
	d = num - k
	diff = 0
	i += 1
if d > 0:
	inc = d // i
	inc += 1 if d % i != 0 else 0
	diff += inc
print(diff)


(n, k) = map(int, input().strip().split())
a = list(map(int, input().strip().split()))
from collections import deque, Counter
temp = Counter(a)
a = deque(sorted(map(lambda x: [x, temp[x]], temp)))
while (k >= a[0][1] or k >= a[-1][1]) and len(a) > 1:
	(cf, f, smf) = (a[0][1], a[0][0], a[1][0])
	(cr, r, smr) = (a[-1][1], a[-1][0], a[-2][0])
	if cf < cr:
		temp = cf * (smf - f)
		if temp <= k:
			k -= temp
			a.popleft()
			a[0][1] += cf
		else:
			factor = k // cf
			temp1 = factor * cf
			k -= temp1
			a[0][0] = f + factor
	else:
		temp = cr * (r - smr)
		if temp <= k:
			k -= temp
			a.pop()
			a[-1][1] += cr
		else:
			factor = k // cr
			temp1 = factor * cr
			k -= temp1
			a[-1][0] = r - factor
print(max(a)[0] - min(a)[0])


(n, k) = map(int, input().split())
s = sorted(map(int, input().split()))
i = 0
j = n - 1
while i < j:
	f = (s[i + 1] - s[i]) * (i + 1) + (s[j] - s[j - 1]) * (n - j)
	if f >= k:
		exit(print(max(0, s[j] - s[i] - k // (i + 1))))
	k -= f
	i += 1
	j -= 1
print(0)