After battling Shikamaru, Tayuya decided that her flute is too predictable, and replaced it with a guitar. The guitar has $6$ strings and an infinite number of frets numbered from $1$. Fretting the fret number $j$ on the $i$-th string produces the note $a_{i} + j$.

Tayuya wants to play a melody of $n$ notes. Each note can be played on different string-fret combination. The easiness of performance depends on the difference between the maximal and the minimal indices of used frets. The less this difference is, the easier it is to perform the technique. Please determine the minimal possible difference.

For example, if $a = [1, 1, 2, 2, 3, 3]$, and the sequence of notes is $4, 11, 11, 12, 12, 13, 13$ (corresponding to the second example), we can play the first note on the first string, and all the other notes on the sixth string. Then the maximal fret will be $10$, the minimal one will be $3$, and the answer is $10 - 3 = 7$, as shown on the picture. [Image] 


-----Input-----

The first line contains $6$ space-separated numbers $a_{1}$, $a_{2}$, ..., $a_{6}$ ($1 \leq a_{i} \leq 10^{9}$) which describe the Tayuya's strings.

The second line contains the only integer $n$ ($1 \leq n \leq 100\,000$) standing for the number of notes in the melody.

The third line consists of $n$ integers $b_{1}$, $b_{2}$, ..., $b_{n}$ ($1 \leq b_{i} \leq 10^{9}$), separated by space. They describe the notes to be played. It's guaranteed that $b_i > a_j$ for all $1\leq i\leq n$ and $1\leq j\leq 6$, in other words, you can play each note on any string.


-----Output-----

Print the minimal possible difference of the maximal and the minimal indices of used frets.


-----Examples-----
Input
1 4 100 10 30 5
6
101 104 105 110 130 200

Output
0

Input
1 1 2 2 3 3
7
13 4 11 12 11 13 12

Output
7



-----Note-----

In the first sample test it is optimal to play the first note on the first string, the second note on the second string, the third note on the sixth string, the fourth note on the fourth string, the fifth note on the fifth string, and the sixth note on the third string. In this case the $100$-th fret is used each time, so the difference is $100 - 100 = 0$. [Image] 

In the second test it's optimal, for example, to play the second note on the first string, and all the other notes on the sixth string. Then the maximal fret will be $10$, the minimal one will be $3$, and the answer is $10 - 3 = 7$. [Image]

Difficulty: HARD
Tags: Sorting

Amortized analysis

Implementation

Complete search

Dynamic programming
Skill types: Dynamic programming

Sorting

Amortized analysis

Complete search

Starter code:

Solutions:
import sys, io, os
BUFSIZE = 8192

class FastIO(io.IOBase):
	newlines = 0

	def __init__(self, file):
		self._fd = file.fileno()
		self.buffer = io.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(io.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()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
from heapq import heappush, heappop
A = sorted(map(int, input().split()), reverse=True)
N = int(input())
q = []
B = sorted(map(int, input().split()))
ma = B[-1] - A[0]
for b in B:
	ba = b - A[0]
	q.append(ba << 4 | 0)
ans = 1 << 62
while True:
	v = heappop(q)
	ba = v >> 4
	idx_A = v & 15
	mi = ba
	an = ma - mi
	if an < ans:
		ans = an
	if idx_A == 5:
		break
	ba += A[idx_A]
	ba -= A[idx_A + 1]
	if ma < ba:
		ma = ba
	heappush(q, ba << 4 | idx_A + 1)
print(ans)


import sys

def techno_c():
	a = list(set(map(int, sys.stdin.readline().split())))
	n = int(sys.stdin.readline())
	b = list(set(map(int, sys.stdin.readline().split())))
	n = len(b)
	m = len(a)
	raz = []
	for j in range(m):
		for i in range(n):
			raz.append([b[i] - a[j], i])
	raz.sort()
	if m == 1:
		return raz[-1][0] - raz[0][0]
	v = [-1] * n
	s = set()
	for i in range(n * m):
		if v[raz[i][1]] >= 0:
			raz[v[raz[i][1]]][0] = -1
		v[raz[i][1]] = i
		s.add(raz[i][1])
		if len(s) == n:
			break
	j = i
	i = min(v)
	ans = raz[j][0] - raz[i][0]
	while j < n * m - 1:
		if len(s) == n:
			ans = min(ans, raz[j][0] - raz[i][0])
			if ans == 0:
				return 0
			k = raz[i][1]
			raz[v[k]][0] = -1
			v[k] = -1
			s.remove(k)
			i += 1
			while raz[i][0] == -1:
				i += 1
		else:
			j += 1
			if v[raz[j][1]] >= 0:
				if v[raz[j][1]] == i:
					i += 1
					while raz[i][0] == -1:
						i += 1
				raz[v[raz[j][1]]][0] = -1
			v[raz[j][1]] = j
			s.add(raz[j][1])
	return ans
rez = techno_c()
sys.stdout.write(str(rez) + '\n')


import sys
import operator

def solve():
	a = [int(x) for x in input().split()]
	n = int(input())
	b = [int(x) for x in input().split()]
	have = []
	arr_append = have.append
	for i in range(0, n):
		for j in range(0, 6):
			arr_append([b[i] - a[j], i])
	cnt = [0] * n
	z = n
	sz = len(have)
	ans = 999999999999
	r = 0
	have.sort(key=operator.itemgetter(0))
	for i in range(0, sz):
		while r < sz and z > 0:
			cnt[have[r][1]] += 1
			if cnt[have[r][1]] == 1:
				z -= 1
			r += 1
		if z > 0:
			break
		ans = min(ans, have[r - 1][0] - have[i][0])
		cnt[have[i][1]] -= 1
		if cnt[have[i][1]] == 0:
			z += 1
	print(ans)

def main(argv):
	solve()

def __starting_point():
	main(sys.argv)
__starting_point()


import sys, math
import io, os
data = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
from bisect import bisect_left as bl, bisect_right as br, insort
from heapq import heapify, heappush, heappop
from collections import defaultdict as dd, deque, Counter
from itertools import permutations, combinations

def mdata():
	return list(map(int, data().split()))

def outl(var):
	sys.stdout.write(' '.join(map(str, var)) + '\n')

def out(var):
	sys.stdout.write(str(var) + '\n')
INF = 10 ** 9
mod = int(1000000000.0) + 7
a = mdata()
n = int(data())
b = mdata()
val = [0] * n
cost = []
cnt = 0
for i in range(n):
	for j in range(6):
		cost.append((b[i] - a[j], i))
cost.sort(key=lambda x: x[0])
(cnt, ind, pre) = (0, 0, 0)
ans = INF
while ind < len(cost):
	if val[cost[ind][1]] == 0:
		cnt += 1
	val[cost[ind][1]] += 1
	while cnt == n:
		ans = min(ans, cost[ind][0] - cost[pre][0])
		val[cost[pre][1]] -= 1
		if val[cost[pre][1]] == 0:
			cnt -= 1
		pre += 1
	ind += 1
out(ans)


import operator
import sys
a = list(set(map(int, sys.stdin.readline().split())))
n = int(input())
c2 = list(set(map(int, sys.stdin.readline().split())))
s = 0
v = [0] * (len(c2) * len(a))
index = 0
n = len(c2)
c = [0] * n
qm = 1000000000.0 + 1
for q in range(len(a)):
	for i in range(len(c2)):
		v[i * (len(a) + 0) + q] = [c2[i] - a[q], i]
v.sort(key=operator.itemgetter(0))
for i in range(len(v)):
	c[v[i][1]] += 1
	if c[v[i][1]] == 1:
		s += 1
	if s == n:
		while c[v[index][1]] > 1:
			c[v[index][1]] -= 1
			index += 1
		if v[i][0] - v[index][0] < qm:
			qm = v[i][0] - v[index][0]
		c[v[index][1]] -= 1
		if c[v[index][1]] == 0:
			s -= 1
		index += 1
sys.stdout.write(str(qm))


import sys
readline = sys.stdin.readline
A = list(map(int, readline().split()))
N = int(readline())
B = list(map(int, readline().split()))
b0 = B[0]
B = B[1:]
INF = 3 * 10 ** 9
if N == 1:
	print(0)
else:
	ans = INF
	for a in A:
		S = b0 - a
		ev = [None] * N
		ev[-1] = (S, S)
		for i in range(N - 1):
			b = B[i]
			(l, r) = (-INF, INF)
			for a in A:
				if b - a == S:
					(l, r) = (S, S)
					break
				if b - a < S:
					l = max(l, b - a)
				else:
					r = min(r, b - a)
			ev[i] = (l, r)
		ev.sort()
		mr = S
		for (l, r) in ev:
			ans = min(ans, mr - l)
			mr = max(mr, r)
	print(ans)


import sys
from math import gcd, sqrt, ceil, log2
from collections import defaultdict, Counter, deque
from bisect import bisect_left, bisect_right
import math
import heapq
from itertools import permutations
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')

def get_sum(bit, i):
	s = 0
	i += 1
	while i > 0:
		s += bit[i]
		i -= i & -i
	return s

def update(bit, n, i, v):
	i += 1
	while i <= n:
		bit[i] += v
		i += i & -i

def modInverse(b, m):
	g = math.gcd(b, m)
	if g != 1:
		return -1
	else:
		return pow(b, m - 2, m)

def primeFactors(n):
	sa = set()
	sa.add(n)
	while n % 2 == 0:
		sa.add(2)
		n = n // 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			sa.add(i)
			n = n // i
	return sa

def seive(n):
	pri = [True] * (n + 1)
	p = 2
	while p * p <= n:
		if pri[p] == True:
			for i in range(p * p, n + 1, p):
				pri[i] = False
		p += 1
	return pri

def check_prim(n):
	if n < 0:
		return False
	for i in range(2, int(sqrt(n)) + 1):
		if n % i == 0:
			return False
	return True

def getZarr(string, z):
	n = len(string)
	(l, r, k) = (0, 0, 0)
	for i in range(1, n):
		if i > r:
			(l, r) = (i, i)
			while r < n and string[r - l] == string[r]:
				r += 1
			z[i] = r - l
			r -= 1
		else:
			k = i - l
			if z[k] < r - i + 1:
				z[i] = z[k]
			else:
				l = i
				while r < n and string[r - l] == string[r]:
					r += 1
				z[i] = r - l
				r -= 1

def search(text, pattern):
	concat = pattern + '$' + text
	l = len(concat)
	z = [0] * l
	getZarr(concat, z)
	ha = []
	for i in range(l):
		if z[i] == len(pattern):
			ha.append(i - len(pattern) - 1)
	return ha

def mergeIntervals(arr):
	arr.sort(key=lambda x: x[0])
	m = []
	s = -10000
	max = -100000
	for i in range(len(arr)):
		a = arr[i]
		if a[0] > max:
			if i != 0:
				m.append([s, max])
			max = a[1]
			s = a[0]
		elif a[1] >= max:
			max = a[1]
	if max != -100000 and [s, max] not in m:
		m.append([s, max])
	return m

class SortedList:

	def __init__(self, iterable=[], _load=200):
		values = sorted(iterable)
		self._len = _len = len(values)
		self._load = _load
		self._lists = _lists = [values[i:i + _load] for i in range(0, _len, _load)]
		self._list_lens = [len(_list) for _list in _lists]
		self._mins = [_list[0] for _list in _lists]
		self._fen_tree = []
		self._rebuild = True

	def _fen_build(self):
		self._fen_tree[:] = self._list_lens
		_fen_tree = self._fen_tree
		for i in range(len(_fen_tree)):
			if i | i + 1 < len(_fen_tree):
				_fen_tree[i | i + 1] += _fen_tree[i]
		self._rebuild = False

	def _fen_update(self, index, value):
		if not self._rebuild:
			_fen_tree = self._fen_tree
			while index < len(_fen_tree):
				_fen_tree[index] += value
				index |= index + 1

	def _fen_query(self, end):
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		x = 0
		while end:
			x += _fen_tree[end - 1]
			end &= end - 1
		return x

	def _fen_findkth(self, k):
		_list_lens = self._list_lens
		if k < _list_lens[0]:
			return (0, k)
		if k >= self._len - _list_lens[-1]:
			return (len(_list_lens) - 1, k + _list_lens[-1] - self._len)
		if self._rebuild:
			self._fen_build()
		_fen_tree = self._fen_tree
		idx = -1
		for d in reversed(range(len(_fen_tree).bit_length())):
			right_idx = idx + (1 << d)
			if right_idx < len(_fen_tree) and k >= _fen_tree[right_idx]:
				idx = right_idx
				k -= _fen_tree[idx]
		return (idx + 1, k)

	def _delete(self, pos, idx):
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len -= 1
		self._fen_update(pos, -1)
		del _lists[pos][idx]
		_list_lens[pos] -= 1
		if _list_lens[pos]:
			_mins[pos] = _lists[pos][0]
		else:
			del _lists[pos]
			del _list_lens[pos]
			del _mins[pos]
			self._rebuild = True

	def _loc_left(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(lo, pos) = (-1, len(_lists) - 1)
		while lo + 1 < pos:
			mi = lo + pos >> 1
			if value <= _mins[mi]:
				pos = mi
			else:
				lo = mi
		if pos and value <= _lists[pos - 1][-1]:
			pos -= 1
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value <= _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def _loc_right(self, value):
		if not self._len:
			return (0, 0)
		_lists = self._lists
		_mins = self._mins
		(pos, hi) = (0, len(_lists))
		while pos + 1 < hi:
			mi = pos + hi >> 1
			if value < _mins[mi]:
				hi = mi
			else:
				pos = mi
		_list = _lists[pos]
		(lo, idx) = (-1, len(_list))
		while lo + 1 < idx:
			mi = lo + idx >> 1
			if value < _list[mi]:
				idx = mi
			else:
				lo = mi
		return (pos, idx)

	def add(self, value):
		_load = self._load
		_lists = self._lists
		_mins = self._mins
		_list_lens = self._list_lens
		self._len += 1
		if _lists:
			(pos, idx) = self._loc_right(value)
			self._fen_update(pos, 1)
			_list = _lists[pos]
			_list.insert(idx, value)
			_list_lens[pos] += 1
			_mins[pos] = _list[0]
			if _load + _load < len(_list):
				_lists.insert(pos + 1, _list[_load:])
				_list_lens.insert(pos + 1, len(_list) - _load)
				_mins.insert(pos + 1, _list[_load])
				_list_lens[pos] = _load
				del _list[_load:]
				self._rebuild = True
		else:
			_lists.append([value])
			_mins.append(value)
			_list_lens.append(1)
			self._rebuild = True

	def discard(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_right(value)
			if idx and _lists[pos][idx - 1] == value:
				self._delete(pos, idx - 1)

	def remove(self, value):
		_len = self._len
		self.discard(value)
		if _len == self._len:
			raise ValueError('{0!r} not in list'.format(value))

	def pop(self, index=-1):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		value = self._lists[pos][idx]
		self._delete(pos, idx)
		return value

	def bisect_left(self, value):
		(pos, idx) = self._loc_left(value)
		return self._fen_query(pos) + idx

	def bisect_right(self, value):
		(pos, idx) = self._loc_right(value)
		return self._fen_query(pos) + idx

	def count(self, value):
		return self.bisect_right(value) - self.bisect_left(value)

	def __len__(self):
		return self._len

	def __getitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		return self._lists[pos][idx]

	def __delitem__(self, index):
		(pos, idx) = self._fen_findkth(self._len + index if index < 0 else index)
		self._delete(pos, idx)

	def __contains__(self, value):
		_lists = self._lists
		if _lists:
			(pos, idx) = self._loc_left(value)
			return idx < len(_lists[pos]) and _lists[pos][idx] == value
		return False

	def __iter__(self):
		return (value for _list in self._lists for value in _list)

	def __reversed__(self):
		return (value for _list in reversed(self._lists) for value in reversed(_list))

	def __repr__(self):
		return 'SortedList({0})'.format(list(self))

def ncr(n, r, p):
	num = den = 1
	for i in range(r):
		num = num * (n - i) % p
		den = den * (i + 1) % p
	return num * pow(den, p - 2, p) % p
l1 = list(map(int, input().split()))
l1.sort()
n = int(input())
l = list(map(int, input().split()))
l.sort()
la = []
for i in range(n):
	for j in range(6):
		la.append([l[i] - l1[j], i])
la.sort()
i = 0
ans = 10 ** 18
seti = set()
j = 0
hash = defaultdict(int)
while j < len(la):
	(a, b) = la[j]
	if len(seti) != n:
		seti.add(b)
		hash[b] += 1
		j += 1
	while len(seti) == n:
		hash[la[i][1]] -= 1
		ans = min(ans, la[j - 1][0] - la[i][0])
		if hash[la[i][1]] == 0:
			seti.remove(la[i][1])
			i += 1
			break
		i += 1
print(ans)


from heapq import *
import sys
input = sys.stdin.readline
a = sorted(map(int, input().split()))
n = int(input())
b = sorted(map(int, input().split()))
u = [6 * (i - a[5]) + 5 for i in b]
heapify(u)
h = b[-1] - a[5]
m = h - u[0] // 6
for i in range(5 * n):
	v = heappop(u)
	if v % 6:
		w = v - 1 + 6 * (a[v % 6] - a[v % 6 - 1])
		if w // 6 > h:
			h = w // 6
		heappush(u, w)
		if h - u[0] // 6 < m:
			m = h - u[0] // 6
	else:
		break
print(m)


import sys
input = sys.stdin.readline
a = list(map(int, input().split()))
a.sort()
n = int(input())
b = list(map(int, input().split()))
b.sort()
res = []
for i in range(6):
	for j in range(n):
		res.append([b[j] - a[i], j])
res.sort()
ans = 10 ** 18
r = 0
c = 0
cnt = [0] * n
for l in range(n * 6):
	while c != n and r < 6 * n:
		cnt[res[r][1]] += 1
		if cnt[res[r][1]] == 1:
			c += 1
		r += 1
	if c != n:
		break
	ans = min(ans, res[r - 1][0] - res[l][0])
	cnt[res[l][1]] -= 1
	if cnt[res[l][1]] == 0:
		c -= 1
print(ans)


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 ** 32, 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: max(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

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
a = list(map(int, input().split()))
n = int(input())
l = list(map(int, input().split()))
a.sort()
l.sort()
d = []
for i in range(n):
	for j in range(6):
		d.append((l[i] - a[j], i))
t = [0] * n
d.sort()
st = 0
end = 0
cur = [0] * n
s = SegmentTree1(cur)
ans = -1
while end < len(d):
	cur[d[end][1]] += 1
	s.__setitem__(d[end][1], cur[d[end][1]])
	if s.query(0, n - 1) == 0:
		end += 1
	else:
		if ans == -1:
			ans = d[end][0] - d[st][0]
		ans = min(ans, d[end][0] - d[st][0])
		cur[d[st][1]] -= 1
		s.__setitem__(d[st][1], cur[d[st][1]])
		cur[d[end][1]] -= 1
		st += 1
	if st > end:
		end = st
print(ans)


import sys
import operator
import array

def solve():
	a = tuple(map(int, input().split()))
	n = int(input())
	b = tuple(map(int, input().split()))
	have = [[]] * (n * 6)
	c = 0
	for i in range(0, n):
		for j in range(0, 6):
			have[c] = (b[i] - a[j], i)
			c += 1
	have.sort(key=operator.itemgetter(0))
	cnt = array.array('L', [0]) * n
	z = n
	sz = len(have)
	ans = 999999999999
	r = 0
	for i in range(0, sz):
		while r < sz and z > 0:
			cnt[have[r][1]] += 1
			if cnt[have[r][1]] == 1:
				z -= 1
			r += 1
		if z > 0:
			break
		ans = min(ans, have[r - 1][0] - have[i][0])
		cnt[have[i][1]] -= 1
		if cnt[have[i][1]] == 0:
			z += 1
	print(ans)

def main(argv):
	solve()
main(sys.argv)


import sys
input = sys.stdin.readline
mod = 10 ** 9 + 7
INF = float('inf')

def getlist():
	return list(map(int, input().split()))

def main():
	A = getlist()
	N = int(input())
	B = getlist()
	T = []
	check = [0] * N
	cnt = 0
	for i in A:
		for (j, b) in enumerate(B):
			T.append((b - i, j))
	T.sort()
	ans = INF
	i = 0
	j = 0
	while True:
		if cnt < N:
			if j >= 6 * N:
				break
			(val, ind) = T[j]
			if check[ind] == 0:
				cnt += 1
			check[ind] += 1
			j += 1
		else:
			if i >= 6 * N:
				break
			(val, ind) = T[i]
			valj = T[j - 1][0]
			ans = min(ans, valj - val)
			if check[ind] == 1:
				cnt -= 1
			check[ind] -= 1
			i += 1
	print(ans)
main()


z1 = list(map(int, input().split()))
import math
from collections import *
s = int(input())
z2 = list(map(int, input().split()))
z1.sort()
z2.sort()
ans = []
for i in range(len(z2)):
	for j in range(6):
		ans.append([z2[i] - z1[j], i])
ans.sort()
al = defaultdict(int)
l = 0
r = 0
mini = math.inf
while l <= r and r < len(ans):
	while r < len(ans):
		if len(al) == s:
			break
		al[ans[r][1]] += 1
		r += 1
	if len(al) != s:
		break
	mini = min(mini, ans[r - 1][0] - ans[l][0])
	al[ans[l][1]] -= 1
	if al[ans[l][1]] == 0:
		al.pop(ans[l][1])
	l += 1
print(mini)


from sys import stdin
a = list(map(int, stdin.readline().split()))
a.sort(reverse=True)
n = int(stdin.readline())
res = []
b = list(map(int, stdin.readline().split()))
for i in range(n):
	bi = b[i]
	for ai in a:
		res.append((bi - ai, i))
res.sort()
cnt = [0] * n
r = 0
c = 0
ans = int(1e+18)
for l in range(n * 6):
	while c != n and r < n * 6:
		cnt[res[r][1]] += 1
		if cnt[res[r][1]] == 1:
			c += 1
		r += 1
	if c != n:
		break
	ans = min(ans, res[r - 1][0] - res[l][0])
	cnt[res[l][1]] -= 1
	if cnt[res[l][1]] == 0:
		c -= 1
print(ans)


import sys
a = list(set(map(int, sys.stdin.readline().split())))
n = int(input())
c2 = list(set(map(int, sys.stdin.readline().split())))
s = 0
n = len(c2)
qm = 10 ** 9 + 1
v = []
c = [0] * n
index = 0
for q in range(len(a)):
	for i in range(len(c2)):
		v.append([c2[i] - a[q], i])
v.sort()
for i in range(len(v)):
	c[v[i][1]] += 1
	if c[v[i][1]] == 1:
		s += 1
	if s == n:
		while c[v[index][1]] > 1:
			c[v[index][1]] -= 1
			index += 1
		if v[i][0] - v[index][0] < qm:
			qm = v[i][0] - v[index][0]
		c[v[index][1]] -= 1
		if c[v[index][1]] == 0:
			s -= 1
		index += 1
sys.stdout.write(str(qm))


la = input().split()
la = list(map(int, la))
t = input()
lb = input().split()
lb = list(map(int, lb))
lenb = len(lb)
l = [(lb[j] - i, j) for i in la for j in range(lenb)]
l.sort()
last = 0
first = 0
l0 = [0] * lenb
l1 = [i for i in range(lenb)]
dic = dict(zip(l1, l0))
dic[l[first][1]] += 1
length = 1
lenl = len(l)
while length < lenb:
	last += 1
	if dic[l[last][1]] == 0:
		length += 1
	dic[l[last][1]] += 1
minnum = l[last][0] - l[first][0]
t = 0
while 1:
	dic[l[first][1]] -= 1
	while dic[l[first][1]] != 0:
		first += 1
		dic[l[first][1]] -= 1
		if minnum > l[last][0] - l[first][0]:
			minnum = l[last][0] - l[first][0]
		if first == last:
			break
	first += 1
	last += 1
	if last >= lenl:
		break
	while dic[l[last][1]] != 0:
		dic[l[last][1]] += 1
		last = last + 1
		if last >= lenl:
			break
	if last >= lenl:
		break
	dic[l[last][1]] += 1
	if minnum > l[last][0] - l[first][0]:
		minnum = l[last][0] - l[first][0]
	if minnum == 0:
		break
print(minnum)


import sys
input = sys.stdin.readline
A = list(map(int, input().split()))
n = int(input())
B = list(map(int, input().split()))
A.sort(reverse=True)
B.sort()
C = [[B[i] - a for a in A] for i in range(n)]
import heapq
H = []
IND = [0] * n
H2 = []
MAX = -1
MINLAST = 1 << 60
for i in range(n):
	heapq.heappush(H, (C[i][0], i))
	heapq.heappush(H2, (C[i][1], i))
	MAX = max(MAX, C[i][0])
	MINLAST = min(MINLAST, C[i][5])
MIN = H[0][0]
ANS = MAX - MIN
while H2:
	(x, ind) = heapq.heappop(H2)
	IND[ind] += 1
	if IND[ind] < 5:
		heapq.heappush(H2, (C[ind][IND[ind] + 1], ind))
	if x > MAX:
		MAX = x
	while H and H[0][0] == ind:
		heapq.heappop(H)
	heapq.heappush(H, (x, ind))
	while H:
		(x, ind) = H[0]
		if C[ind][IND[ind]] != x:
			heapq.heappop(H)
		else:
			break
	if H:
		MIN = min(MINLAST, H[0][0])
	ANS = min(ANS, MAX - MIN)
print(ANS)


from collections import deque as _deque
from itertools import chain as _chain
import sys as _sys

def main():
	a_seq = tuple(_read_ints())
	(n,) = _read_ints()
	notes = tuple(_read_ints())
	result = find_minimal_melody_difficulty(a_seq, notes)
	print(result)

def find_minimal_melody_difficulty(strings_values, notes):
	strings_values = set(strings_values)
	strings_values = sorted(strings_values, reverse=True)
	if len(strings_values) == 1:
		return max(notes) - min(notes)
	frets_by_notes_indices = [[note - x for x in strings_values] for note in notes]
	del strings_values
	del notes
	max_from_initially_selected_frets = max((frets[0] for frets in frets_by_notes_indices))
	for frets in frets_by_notes_indices:
		i_first_interesting_fret = 0
		while i_first_interesting_fret + 1 < len(frets) and frets[i_first_interesting_fret + 1] <= max_from_initially_selected_frets:
			i_first_interesting_fret += 1
		frets[:] = frets[i_first_interesting_fret:]
	selected_frets = [frets[0] for frets in frets_by_notes_indices]
	selected_frets.sort()
	selected_frets = _deque(selected_frets)
	available_selections = _chain.from_iterable((list(zip(frets[1:], frets[0:])) for frets in frets_by_notes_indices))
	available_selections = sorted(available_selections)
	frets_to_unselect = dict()
	for frets in frets_by_notes_indices:
		for fret in frets:
			frets_to_unselect[fret] = 0
	min_selected_fret = selected_frets[0]
	max_selected_fret = max(selected_frets)
	result = max_selected_fret - min_selected_fret
	for (new_fret, fret_to_unselect) in available_selections:
		frets_to_unselect[fret_to_unselect] += 1
		_clean_deque_begin(selected_frets, frets_to_unselect)
		selected_frets.append(new_fret)
		min_selected_fret = selected_frets[0]
		max_selected_fret = new_fret
		result = min(result, max_selected_fret - min_selected_fret)
	return result

def _clean_deque_begin(deque, deletions_ns):
	while deque and deletions_ns[deque[0]] > 0:
		deleted_element = deque.popleft()
		deletions_ns[deleted_element] -= 1

def _read_line():
	result = _sys.stdin.readline()
	assert result[-1] == '\n'
	return result[:-1]

def _read_ints():
	return list(map(int, _read_line().split()))

def __starting_point():
	main()
__starting_point()


def main():
	a = [int(x) for x in input().split()]
	n = int(input())
	b = [int(x) for x in input().split()]
	fretsAndNoteNo = []
	for base in a:
		for (noteNo, note) in enumerate(b):
			fret = note - base
			fretsAndNoteNo.append((fret, noteNo))
	fretsAndNoteNo.sort(key=lambda x: x[0])
	ans = float('inf')
	noteNoCnts = [0 for _ in range(n)]
	totalUniqueNotesInSegment = 0
	left = 0
	for (right, (fretNo, noteNo)) in enumerate(fretsAndNoteNo):
		noteNoCnts[noteNo] += 1
		if noteNoCnts[noteNo] == 1:
			totalUniqueNotesInSegment += 1
			while totalUniqueNotesInSegment == n:
				diff = fretNo - fretsAndNoteNo[left][0]
				ans = min(ans, diff)
				noteNoCnts[fretsAndNoteNo[left][1]] -= 1
				if noteNoCnts[fretsAndNoteNo[left][1]] == 0:
					totalUniqueNotesInSegment -= 1
				left += 1
	print(ans)
	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]))
main()


ss = sorted(set(map(int, input().split())))
input()
nn = sorted(set(map(int, input().split())))
if len(nn) == 1:
	print(0)
elif len(ss) == 1:
	print(nn[-1] - nn[0])
else:
	n0 = nn[0]
	ans = int(1000000000.0)
	for s in ss:
		n0f = n0 - s
		lrs = []
		for n in nn[1:]:
			l = r = int(1000000000.0)
			for s in ss:
				f = n - s
				if f == n0f:
					break
				if f > n0f:
					r = min(r, f - n0f)
				else:
					l = min(l, n0f - f)
			else:
				lrs.append([l, r])
		if not lrs:
			ans = 0
			break
		lrs.sort()
		rls = sorted(lrs, key=lambda x: x[1], reverse=True)
		ansc = rls[0][1]
		nrls = len(rls)
		ir = 0
		for lr in lrs:
			lr[1] = 0
			while ir < nrls and rls[ir][1] == 0:
				ir += 1
			r = rls[ir][1] if ir < nrls else 0
			ansc = min(ansc, lr[0] + r)
		ans = min(ans, ansc)
	print(ans)


import sys
input = sys.stdin.readline

def getInts():
	return [int(s) for s in input().strip().split()]

def getInt():
	return int(input().strip())

def solve():
	A = getInts()
	M = getInt()
	B = getInts()
	X = []
	P = []
	for (i, b) in enumerate(B):
		for a in A:
			P.append((b - a, i))
	P.sort()
	i = 0
	j = -1
	counts = [0] * M
	sset = set()
	ans = 2 * 10 ** 9
	MAX = M * 6
	set_len = 0
	while i < MAX:
		while set_len < M and j < MAX:
			j += 1
			try:
				if not counts[P[j][1]]:
					set_len += 1
				counts[P[j][1]] += 1
			except:
				break
		if set_len < M:
			break
		z = P[i][1]
		ans = min(ans, P[j][0] - P[i][0])
		counts[z] -= 1
		if not counts[z]:
			set_len -= 1
		i += 1
	return ans
print(solve())


a = list(map(int, input().split()))
n = int(input())
s = list(map(int, input().split()))
b = []
for i in range(n):
	for j in a:
		b.append((s[i] - j) * n + i)
b = sorted(b)
cs = {}
i = j = 0
ans = 10 ** 18
cs[b[0] % n] = cs.get(b[0] % n, 0) + 1
z = len(b)
while j < z:
	while j + 1 < z and len(cs) < n:
		j += 1
		cs[b[j] % n] = cs.get(b[j] % n, 0) + 1
	while len(cs) == n:
		ans = min(ans, b[j] // n - b[i] // n)
		cs[b[i] % n] -= 1
		if cs[b[i] % n] == 0:
			cs.pop(b[i] % n)
		i += 1
	if j + 1 == z:
		break
print(ans)


a = list(map(int, input().split()))
n = int(input())
s = list(map(int, input().split()))
b = []
for i in range(n):
	for j in a:
		b.append((s[i] - j) * n + i)
b.sort()
cs = {}
i = j = 0
ans = 10 ** 18

def dd(w):
	cs[w] = cs.get(w, 0) + 1

def em(w):
	cs[w] -= 1
	if cs[w] == 0:
		cs.pop(w)
dd(b[0] % n)
while j < len(b):
	while j + 1 < len(b) and len(cs) < n:
		j += 1
		dd(b[j] % n)
	while len(cs) == n:
		ans = min(ans, b[j] // n - b[i] // n)
		em(b[i] % n)
		i += 1
	if j + 1 == len(b):
		break
print(ans)


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()

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

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

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

def print_list(l):
	print(' '.join(map(str, l)))
from heapq import *
a = RLL()
a.sort(reverse=True)
n = N()
b = RLL()
res = float('inf')
heap = [(b[i] - a[0], i) for i in range(n)]
heapify(heap)
m = max(b) - a[0]
count = [0] * n
while 1:
	(v, i) = heap[0]
	res = min(res, m - v)
	count[i] += 1
	if count[i] == 6:
		break
	t = b[i] - a[count[i]]
	m = max(m, t)
	heapreplace(heap, (t, i))
print(res)


from collections import deque
from collections import OrderedDict
from queue import PriorityQueue
from operator import attrgetter
import math
import sys
import os
import threading
import bisect
import operator
import queue
import heapq
from atexit import register
from io import BytesIO
import io
from sys import stdin, stdout
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 Pair:

	def __init__(self, first, second):
		self.first = first
		self.second = second
arA = list(map(int, input().split()))
n = int(input())
arB = list(map(int, input().split()))
if n == 1:
	print(0)
	sys.exit(0)
arFul = []
for i in range(n):
	for j in range(6):
		arFul.append(Pair(arB[i] - arA[j], i))
arFul.sort(key=attrgetter('first'))
dp = [0] * 100005
needFound = -1
isAll = False
firstFound = 0
answer = 1000000000
l = 0
Pere = False
for i in range(n * 6):
	if firstFound != n:
		if dp[arFul[i].second] == 0:
			firstFound += 1
		dp[arFul[i].second] += 1
		if firstFound == n:
			if isAll == False:
				isAll = True
				answer = arFul[i].first - arFul[0].first
	if isAll == True:
		if Pere == True:
			dp[arFul[i].second] += 1
		else:
			Pere = True
		while l < n * 6 and dp[arFul[l].second] != 1:
			dp[arFul[l].second] -= 1
			l += 1
		answer = min(answer, arFul[i].first - arFul[l].first)
print(answer)


import math
import sys, bisect
from heapq import *
from itertools import *
from collections import *
sys.setrecursionlimit(10 ** 6)
I = lambda : int(sys.stdin.readline())
neo = lambda : map(int, sys.stdin.readline().split())
Neo = lambda : list(map(int, sys.stdin.readline().split()))
a = Neo()
n = I()
b = Neo()
a.sort()
b.sort()
c = [0 for i in range(n)]
mn = 10000000000
pq = []
for i in range(n):
	heappush(pq, (-b[i] + a[c[i]], i))
	mn = min(mn, b[i] - a[c[i]])
x = 10000000000
while True:
	td = heappop(pq)
	i = td[1]
	x = min(x, -td[0] - mn)
	c[i] += 1
	if c[i] == 6:
		break
	mn = min(b[i] - a[c[i]], mn)
	heappush(pq, (-b[i] + a[c[i]], i))
print(x)


from sys import stdin
input = stdin.readline
a = sorted([int(i) for i in input().split()])
n = int(input())
b = sorted([int(i) for i in input().split()])
c = []
for i in range(n):
	c += [[b[i] - a[j], i] for j in range(6)]
c.sort()
d = [0] * n
e = 0
ans = 10 ** 10
u = 0
for i in range(len(c)):
	while u < len(c) and e < n:
		x = c[u][1]
		if d[x] == 0:
			e += 1
		d[x] += 1
		u += 1
	if e == n:
		ans = min(ans, c[u - 1][0] - c[i][0])
	x = c[i][1]
	d[x] -= 1
	if d[x] == 0:
		e -= 1
print(ans)


arr = [int(x) for x in input().split()]
arr = list(set(arr))
n = int(input())
b = [int(x) for x in input().split()]
temp = []
b = list(set(b))
n = len(b)
for i in range(n):
	for j in arr:
		temp.append((b[i] - j, i))
temp.sort()
(start, end) = (0, 0)
l = len(temp)
curr = 0
ans = 10000000000000
d = [0 for i in range(n)]
while end < l or (end == l and curr >= n):
	if curr < n:
		if d[temp[end][1]] == 0:
			curr += 1
		d[temp[end][1]] += 1
		end += 1
	else:
		ans = min(ans, temp[end - 1][0] - temp[start][0])
		d[temp[start][1]] -= 1
		if d[temp[start][1]] == 0:
			curr -= 1
		start += 1
print(ans)


import sys
sys.setrecursionlimit(10 ** 5)
int1 = lambda x: int(x) - 1
p2D = lambda x: print(*x, sep='\n')

def II():
	return int(sys.stdin.buffer.readline())

def MI():
	return map(int, sys.stdin.buffer.readline().split())

def LI():
	return list(map(int, sys.stdin.buffer.readline().split()))

def LLI(rows_number):
	return [LI() for _ in range(rows_number)]

def BI():
	return sys.stdin.buffer.readline().rstrip()

def SI():
	return sys.stdin.buffer.readline().rstrip().decode()
inf = 10 ** 16
aa = LI()
n = II()
bb = LI()
di = []
for a in aa:
	for (i, b) in enumerate(bb):
		di.append((b - a, i))
di.sort()
cnt = [0] * n
now = 0
for (r, (d, i)) in enumerate(di):
	if cnt[i] == 0:
		now += 1
	cnt[i] += 1
	if now == n:
		break
ans = inf
for (d0, i0) in di:
	while r + 1 < n * 6 and now < n:
		r += 1
		i1 = di[r][1]
		if cnt[i1] == 0:
			now += 1
		cnt[i1] += 1
	if now < n:
		break
	ans = min(ans, di[r][0] - d0)
	cnt[i0] -= 1
	if cnt[i0] == 0:
		now -= 1
print(ans)


import os, 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')
a = list(map(int, input().split()))
a.sort()
n = int(input())
b = list(map(int, input().split()))
d = dict()
for i in b:
	d[i] = 0
ar = [[]] * (6 * len(d))
t = 0
for i in sorted(d):
	for j in a:
		ar[t] = [i - j, i]
		t += 1
ar.sort()
ans = 10 ** 18
i = j = 0
ck = set()
while j < len(ar) and len(ck) != len(d):
	d[ar[j][1]] = d.get(ar[j][1], 0) + 1
	ck.add(ar[j][1])
	j += 1
ans = min(ans, ar[j - 1][0] - ar[i][0])
while j < len(ar):
	d[ar[i][1]] -= 1
	if d[ar[i][1]] == 0:
		ck.remove(ar[i][1])
	i += 1
	if len(ck) == len(d):
		ans = min(ans, ar[j - 1][0] - ar[i][0])
	else:
		while j < len(ar) and len(ck) != len(d):
			d[ar[j][1]] = d.get(ar[j][1], 0) + 1
			ck.add(ar[j][1])
			j += 1
		if len(ck) == len(d):
			ans = min(ans, ar[j - 1][0] - ar[i][0])
print(ans)


import sys
import heapq
input = sys.stdin.readline
a = list(set(map(int, input().split())))
k = len(a)
n = int(input())
b = list(set(map(int, input().split())))
n = len(b)
a.sort()
b.sort()
c = [0 for i in range(n)]
mn = float('inf')
pq = [(b[i] - a[j], i) for i in range(n) for j in range(k)]
pq.sort(reverse=True)
mn = b[0] - a[0]
cnt = [0] * n
x = float('inf')
for (d, i) in pq:
	x = min(x, d - mn)
	cnt[i] += 1
	if cnt[i] == k:
		break
	mn = min(b[i] - a[cnt[i]], mn)
print(x)


import heapq
import sys
input = sys.stdin.readline

def main():
	alst = list(map(int, input().split()))
	n = int(input())
	blst = list(map(int, input().split()))
	alst.sort(reverse=True)
	blst.sort()
	lst = []
	for b in blst:
		tmp = [b - a for a in alst]
		lst.append(tmp)
	hq = []
	max_ = 0
	for i in range(n):
		hq.append((lst[i][0], i, 0))
		max_ = max(max_, lst[i][0])
	heapq.heapify(hq)
	ans = max_ - hq[0][0]
	while 1:
		(_, i, pos) = heapq.heappop(hq)
		if pos == 5:
			break
		max_ = max(max_, lst[i][pos + 1])
		heapq.heappush(hq, (lst[i][pos + 1], i, pos + 1))
		ans = min(ans, max_ - hq[0][0])
	print(ans)
main()


a = list(map(int, input().split()))
n = int(input())
s = list(map(int, input().split()))
b = []
i = 0
j = 0
ans = 10 ** 18
cs = [0] * n
nz = 1
z = n * 6
for y in range(n):
	for x in a:
		b.append((s[y] - x) * n + y)
b.sort()
cs[b[0] % n] += 1
while j + 1 < z:
	while j + 1 < z and nz < n:
		j += 1
		nz += cs[b[j] % n] < 1
		cs[b[j] % n] += 1
	while nz == n:
		ans = min(ans, b[j] // n - b[i] // n)
		cs[b[i] % n] -= 1
		nz -= cs[b[i] % n] == 0
		i += 1
print(ans)


from itertools import chain as _chain
import sys as _sys

def main():
	a_seq = tuple(_read_ints())
	(n,) = _read_ints()
	notes = tuple(_read_ints())
	result = find_minimal_melody_difficulty(a_seq, notes)
	print(result)

def find_minimal_melody_difficulty(strings_values, notes):
	strings_values = set(strings_values)
	strings_values = sorted(strings_values, reverse=True)
	if len(strings_values) == 1:
		return max(notes) - min(notes)
	frets_by_notes_indices = [[note - x for x in strings_values] for note in notes]
	del strings_values
	del notes
	max_initially_selected_fret = max((frets[0] for frets in frets_by_notes_indices))
	for frets in frets_by_notes_indices:
		i_first_interesting_fret = 0
		while i_first_interesting_fret + 1 < len(frets) and frets[i_first_interesting_fret + 1] <= max_initially_selected_fret:
			i_first_interesting_fret += 1
		frets[:] = frets[i_first_interesting_fret:]
	sorted_frets = sorted(_chain.from_iterable(frets_by_notes_indices))
	initially_selected_frets = [frets[0] for frets in frets_by_notes_indices]
	min_initially_selected = min(initially_selected_frets)
	i_first_selected = sorted_frets.index(min_initially_selected)
	while i_first_selected + 1 < len(sorted_frets) and sorted_frets[i_first_selected + 1] == min_initially_selected:
		i_first_selected += 1
	i_first_selected -= initially_selected_frets.count(min_initially_selected) - 1
	i_last_selected = i_first_selected + len(initially_selected_frets) - 1
	available_selections = _chain.from_iterable((zip(frets[1:], frets[0:]) for frets in frets_by_notes_indices))
	available_selections = sorted(available_selections)
	frets_to_unselect = dict()
	for frets in frets_by_notes_indices:
		for fret in frets:
			frets_to_unselect[fret] = 0
	result = sorted_frets[i_last_selected] - sorted_frets[i_first_selected]
	for (new_fret, fret_to_unselect) in available_selections:
		frets_to_unselect[fret_to_unselect] += 1
		i_first_selected = _shift_index_skipping(sorted_frets, i_first_selected, frets_to_unselect)
		i_last_selected += 1
		current_maxmin_difference = sorted_frets[i_last_selected] - sorted_frets[i_first_selected]
		if current_maxmin_difference < result:
			result = current_maxmin_difference
	return result

def _shift_index_skipping(sorted_seq, index, deletions_ns):
	while index < len(sorted_seq) and deletions_ns[sorted_seq[index]] > 0:
		deleted_element = sorted_seq[index]
		index += 1
		deletions_ns[deleted_element] -= 1
	return index

def _read_line():
	result = _sys.stdin.readline()
	assert result[-1] == '\n'
	return result[:-1]

def _read_ints():
	return map(int, _read_line().split())
main()


import sys
import heapq
input = sys.stdin.readline
a = list(set(map(int, input().split())))
k = len(a)
n = int(input())
b = list(set(map(int, input().split())))
n = len(b)
a.sort()
b.sort()
c = [0 for i in range(n)]
mn = float('inf')
pq = []
for i in range(n):
	heapq.heappush(pq, (-b[i] + a[c[i]], i))
	mn = min(mn, b[i] - a[c[i]])
x = float('inf')
while True:
	td = heapq.heappop(pq)
	i = td[1]
	x = min(x, -td[0] - mn)
	c[i] += 1
	if c[i] == k:
		break
	mn = min(b[i] - a[c[i]], mn)
	heapq.heappush(pq, (-b[i] + a[c[i]], i))
print(x)


from sys import stdin
import heapq
import sys
a = list(map(int, stdin.readline().split()))
a.sort()
a.reverse()
n = int(stdin.readline())
b = list(map(int, stdin.readline().split()))
state = [0] * n
minq = []
maxq = []
for i in range(n):
	minq.append((b[i] - a[0], i))
	maxq.append((-1 * (b[i] - a[0]), i))
heapq.heapify(minq)
heapq.heapify(maxq)
ans = float('inf')
for i in range(5 * n):
	while len(maxq) > 0 and maxq[0][0] != -1 * (b[maxq[0][1]] - a[state[maxq[0][1]]]):
		heapq.heappop(maxq)
	ans = min(ans, -1 * maxq[0][0] - minq[0][0])
	(tmp, index) = heapq.heappop(minq)
	state[index] += 1
	if state[index] >= 6:
		break
	ppp = b[index] - a[state[index]]
	heapq.heappush(minq, (ppp, index))
	heapq.heappush(maxq, (-1 * ppp, index))
print(ans)


from collections import defaultdict as df
import os
import sys
from io import BytesIO, IOBase
_str = str
str = lambda x=b'': x if type(x) is bytes else _str(x).encode()
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')
strings = list(map(int, input().split()))
n = int(input())
arr = list(map(int, input().split()))
narr = []
for (idx, each) in enumerate(arr):
	for st in strings:
		narr.append((each - st, idx))
narr.sort()
cnt_d = dict()
ans = 1000000
start = 0
end = 0
nn = len(narr)
d_len = 0
while True:
	(val, id) = narr[end]
	if id not in cnt_d:
		cnt_d[id] = 1
		d_len += 1
	else:
		cnt_d[id] += 1
	if len(cnt_d) >= n:
		ans = narr[end][0] - narr[start][0]
		break
	end += 1
for start in range(nn):
	(_, id) = narr[start]
	cnt_d[id] -= 1
	if not cnt_d[id]:
		d_len -= 1
	while d_len < n:
		end += 1
		if end >= nn:
			print(ans)
			exit()
		(val, id) = narr[end]
		if not cnt_d[id]:
			d_len += 1
		cnt_d[id] += 1
	ans = min(ans, val - narr[start + 1][0])
print(ans)


from collections import Counter

def main():
	a = list(map(int, input().split()))
	n = int(input())
	b = list(map(int, input().split()))
	x = []
	for i in a:
		for j in b:
			x.append((j - i, j))
	x.sort()
	j = 0
	r = float('inf')
	c = len(set(b))
	d = Counter()
	for i in range(n * 6):
		while len(d) < c and j < n * 6:
			d[x[j][1]] += 1
			j += 1
		if len(d) < c:
			break
		if x[j - 1][0] - x[i][0] < r:
			r = x[j - 1][0] - x[i][0]
		d[x[i][1]] -= 1
		if d[x[i][1]] == 0:
			d.pop(x[i][1])
	print(r)
main()


import sys
import os
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 inf
from collections import deque
from heapq import heappush, heappop
a = list(map(int, input().split()))
a.sort(reverse=True)
n = int(input())
frets = list(map(int, input().split()))
frets.sort()
(dq_list, heap) = ([], [])
for x in frets:
	dq_list.append(deque([x - v for v in a]))
(ans, R) = (inf, -inf)
for i in range(n):
	v = dq_list[i].popleft()
	R = max(R, v)
	heappush(heap, (v, i))
ans = R - heap[0][0]
while heap:
	(v, i) = heappop(heap)
	if not dq_list[i]:
		break
	nxt = dq_list[i].popleft()
	R = max(R, nxt)
	heappush(heap, (nxt, i))
	ans = min(ans, R - heap[0][0])
print(ans)


a = list(map(int, input().split()))
n = int(input())
notes = list(map(int, input().split()))
(s, used) = ([], [0 for i in range(n * 6)])
for i in range(n):
	for j in a:
		s.append((notes[i] - j, i))
(l, res, cnt) = (0, 10 ** 20, 0)
s.sort()
for r in range(len(s)):
	used[s[r][1]] += 1
	if used[s[r][1]] == 1:
		cnt += 1
	while cnt == n:
		res = min(res, s[r][0] - s[l][0])
		used[s[l][1]] -= 1
		if used[s[l][1]] == 0:
			cnt -= 1
		l += 1
print(res)


import io
import os
from collections import Counter, defaultdict, deque

def solve(A, N, B):
	costs = []
	indices = []
	for (i, a) in enumerate(A):
		for (j, b) in enumerate(B):
			costs.append(b - a)
			indices.append(j)
	order = list(range(len(costs)))
	order.sort(key=lambda i: costs[i])
	costs2 = []
	indices2 = []
	for i in order:
		costs2.append(costs[i])
		indices2.append(indices[i])
	costs = costs2
	indices = indices2
	window = Counter()
	windowC = deque()
	windowI = deque()
	tail = 0
	best = float('inf')
	for i in range(len(costs)):
		b = costs[i]
		j = indices[i]
		while len(window) != N and tail < len(costs):
			bb = costs[tail]
			jj = indices[tail]
			window[jj] += 1
			windowC.append(bb)
			windowI.append(jj)
			tail += 1
		if len(window) != N:
			break
		best = min(best, windowC[-1] - windowC[0])
		bb = windowC.popleft()
		jj = windowI.popleft()
		window[jj] -= 1
		if window[jj] == 0:
			del window[jj]
	return best
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
A = [int(x) for x in input().split()]
(N,) = [int(x) for x in input().split()]
B = [int(x) for x in input().split()]
ans = solve(A, N, B)
print(ans)


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
from collections import defaultdict
from collections import deque
import threading
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 SegmentTree:

	def __init__(self, data, default=-10 ** 6, func=lambda a, b: max(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 SegmentTree1:

	def __init__(self, data, default=10 ** 6, 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)
MOD = 10 ** 9 + 7

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
mod = 10 ** 9 + 7
omod = 998244353
prime = [True for i in range(50001)]
pp = []

def SieveOfEratosthenes(n=50000):
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	for i in range(50001):
		if prime[i]:
			pp.append(i)
a = list(map(int, input().split()))
n = int(input())
l = list(map(int, input().split()))
a.sort()
l.sort()
d = []
for i in range(n):
	for j in range(6):
		d.append((l[i] - a[j], i))
t = [0] * n
d.sort()
st = 0
end = 0
cur = [0] * n
s = SegmentTree1(cur)
ans = -1
while end < len(d):
	cur[d[end][1]] += 1
	s.__setitem__(d[end][1], cur[d[end][1]])
	if s.query(0, n - 1) == 0:
		end += 1
	else:
		if ans == -1:
			ans = d[end][0] - d[st][0]
		ans = min(ans, d[end][0] - d[st][0])
		cur[d[st][1]] -= 1
		s.__setitem__(d[st][1], cur[d[st][1]])
		cur[d[end][1]] -= 1
		st += 1
	if st > end:
		end = st
print(ans)


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()

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

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

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

def print_list(l):
	print(' '.join(map(str, l)))
import bisect as bs
a = RLL()
a.sort()
n = N()
b = RLL()
data = [(b[i] - a[j], i) for i in range(n) for j in range(6)]
data.sort()
res = float('inf')
now = [0] * n
count = 0
(l, r) = (0, 0)
mn = 6 * n
while 1:
	while count < n and r < mn:
		k = data[r][1]
		now[k] += 1
		if now[k] == 1:
			count += 1
		r += 1
	if count < n:
		break
	while count == n:
		k = data[l][1]
		now[k] -= 1
		if now[k] == 0:
			count -= 1
		l += 1
	res = min(data[r - 1][0] - data[l - 1][0], res)
print(res)


mod = 1000000007
eps = 10 ** (-9)

def main():
	import sys
	input = sys.stdin.readline
	A = list(map(int, input().split()))
	N = int(input())
	B = list(map(int, input().split()))
	A.sort()
	B.sort()
	cnt = {i: 0 for i in range(N)}
	C = []
	for i in range(N):
		for j in range(6):
			C.append((B[i] - A[j], i))
	C.sort(key=lambda x: x[0])
	r = -1
	zero_num = N
	ans = 10 ** 10
	for l in range(6 * N):
		if l > 0:
			cnt[C[l - 1][1]] -= 1
			if cnt[C[l - 1][1]] == 0:
				zero_num += 1
		while zero_num != 0:
			r += 1
			if r == 6 * N:
				print(ans)
				exit()
			(_, i) = C[r]
			cnt[i] += 1
			if cnt[i] == 1:
				zero_num -= 1
		ans = min(ans, C[r][0] - C[l][0])
	print(ans)
main()