There are $n$ points on a plane. The $i$-th point has coordinates $(x_i, y_i)$. You have two horizontal platforms, both of length $k$. Each platform can be placed anywhere on a plane but it should be placed horizontally (on the same $y$-coordinate) and have integer borders. If the left border of the platform is $(x, y)$ then the right border is $(x + k, y)$ and all points between borders (including borders) belong to the platform.

Note that platforms can share common points (overlap) and it is not necessary to place both platforms on the same $y$-coordinate.

When you place both platforms on a plane, all points start falling down decreasing their $y$-coordinate. If a point collides with some platform at some moment, the point stops and is saved. Points which never collide with any platform are lost.

Your task is to find the maximum number of points you can save if you place both platforms optimally.

You have to answer $t$ independent test cases.

For better understanding, please read the Note section below to see a picture for the first test case.


-----Input-----

The first line of the input contains one integer $t$ ($1 \le t \le 2 \cdot 10^4$) — the number of test cases. Then $t$ test cases follow.

The first line of the test case contains two integers $n$ and $k$ ($1 \le n \le 2 \cdot 10^5$; $1 \le k \le 10^9$) — the number of points and the length of each platform, respectively. The second line of the test case contains $n$ integers $x_1, x_2, \dots, x_n$ ($1 \le x_i \le 10^9$), where $x_i$ is $x$-coordinate of the $i$-th point. The third line of the input contains $n$ integers $y_1, y_2, \dots, y_n$ ($1 \le y_i \le 10^9$), where $y_i$ is $y$-coordinate of the $i$-th point. All points are distinct (there is no pair $1 \le i < j \le n$ such that $x_i = x_j$ and $y_i = y_j$).

It is guaranteed that the sum of $n$ does not exceed $2 \cdot 10^5$ ($\sum n \le 2 \cdot 10^5$).


-----Output-----

For each test case, print the answer: the maximum number of points you can save if you place both platforms optimally.


-----Example-----
Input
4
7 1
1 5 2 3 1 5 4
1 3 6 7 2 5 4
1 1
1000000000
1000000000
5 10
10 7 5 15 8
20 199 192 219 1904
10 10
15 19 8 17 20 10 9 2 10 19
12 13 6 17 1 14 7 9 19 3

Output
6
1
5
10



-----Note-----

The picture corresponding to the first test case of the example:

[Image]

Blue dots represent the points, red segments represent the platforms. One of the possible ways is to place the first platform between points $(1, -1)$ and $(2, -1)$ and the second one between points $(4, 3)$ and $(5, 3)$. Vectors represent how the points will fall down. As you can see, the only point we can't save is the point $(3, 7)$ so it falls down infinitely and will be lost. It can be proven that we can't achieve better answer here. Also note that the point $(5, 3)$ doesn't fall at all because it is already on the platform.

Difficulty: MEDIUM_HARD

Solutions:
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	l.sort()
	l3 = []
	l4 = [0]
	kk = 1
	count = 0
	c = 0
	i = 0
	j = 0
	ans = 0
	while i < n and j < n:
		if l[j] - l[i] <= k and j >= i:
			ans = max(ans, j - i + 1)
			l3.append(ans)
			j += 1
		else:
			i += 1
	i = n - 1
	j = n - 1
	ans = 0
	while i > 0 and j > 0:
		if l[i] - l[j] <= k and j <= i:
			ans = max(ans, i - j + 1)
			l4.append(ans)
			j -= 1
		else:
			i -= 1
	c = len(l3)
	ans = 0
	for i in range(c):
		ans = max(ans, l3[i] + l4[n - i - 1])
	print(ans)


import bisect
test = int(input())
for _ in range(test):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	yp = list(map(int, input().split()))
	x.sort()
	ans = 0
	ma = [0] * (n + 3)
	for i in range(n - 1, -1, -1):
		(l, r) = (x[i], x[i] + k)
		ll = bisect.bisect_left(x, l)
		rr = bisect.bisect_right(x, r)
		now = rr - ll
		ma[i] = max(now, ma[i + 1])
		ans = max(ans, now + ma[rr])
	print(ans)


for t in range(int(input())):
	(n, k) = map(int, input().split())
	xs = sorted(list(map(int, input().split())))
	input()
	best = 0
	i = j = 0
	while j < n:
		while j < n and xs[j] <= xs[i] + k:
			j += 1
		if best < j - i:
			best = j - i
			best_start = i
			best_end = j
		i += 1
	i = j = 0
	best2 = 0
	while j < best_start:
		while j < best_start and xs[j] <= xs[i] + k:
			j += 1
		if best2 < j - i:
			best2 = j - i
		i += 1
	i = j = best_end
	while j < n:
		while j < n and xs[j] <= xs[i] + k:
			j += 1
		if best2 < j - i:
			best2 = j - i
		i += 1
	best += best2
	j = best_start
	while j > -1 and xs[j] + k >= xs[best_start]:
		j -= 1
	last = best_start - j
	goodies = [(best_start, last)]
	if j == -1:
		j = 0
	for i in range(best_start + 1, best_end - 1):
		while xs[j] + k < xs[i]:
			j += 1
		if i - j + 1 > last:
			last = i - j + 1
			goodies.append((i, last))
	j = best_end - 1
	best2 = 0
	while j < n and xs[j] + k >= xs[best_end - 1]:
		j += 1
	if j == n:
		j = n - 1
	for i in range(best_end - 1, best_start, -1):
		while xs[i] + k < xs[j]:
			j -= 1
		if i == goodies[-1][0]:
			goodies.pop()
		if j - i + 1 + goodies[-1][1] > best2:
			best2 = j - i + 1 + goodies[-1][1]
	print(max(best, best2))


from sys import stdin, stdout
t = int(stdin.readline())
for _ in range(t):
	(n, k) = map(int, stdin.readline().split())
	x = list(map(int, stdin.readline().split()))
	y = stdin.readline()
	if n == 1:
		print(1)
		continue
	endi = [1] * n
	starti = [1] * n
	x.sort()
	curri = 0
	i = 1
	while i < n:
		if x[i] - x[curri] < k:
			endi[i] = i - curri + 1
			i += 1
		elif x[i] - x[curri] == k:
			endi[i] = i - curri + 1
			i += 1
		else:
			curri += 1
	for i in range(1, n):
		endi[i] = max(endi[i], endi[i - 1])
	curri = n - 1
	i = n - 2
	while i >= 0:
		if x[curri] - x[i] < k:
			starti[i] = curri - i + 1
			i -= 1
		elif x[curri] - x[i] == k:
			starti[i] = curri - i + 1
			i -= 1
		else:
			curri -= 1
	for i in range(n - 2, -1, -1):
		starti[i] = max(starti[i], starti[i + 1])
	maxi = x.count(x[0])
	for i in range(n - 1):
		s = endi[i] + starti[i + 1]
		if s > maxi:
			maxi = s
	print(maxi)


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
for j in range(int(input())):
	(n, k) = map(int, input().split())
	xcord = list(map(int, input().split()))
	ycord = input()
	xcord.sort()
	lbound = []
	for s in range(n):
		ind = min(bisect.bisect_left(xcord, xcord[s] + k + 1), len(xcord) - 1)
		if xcord[ind] > xcord[s] + k:
			ind -= 1
		points = ind + 1 - s
		lbound.append(points)
	maxsofar = [lbound[-1]]
	for s in range(n - 2, -1, -1):
		maxsofar.append(max(maxsofar[-1], lbound[s]))
	maxsofar.reverse()
	maxans = 0
	for s in range(n):
		p1 = lbound[s]
		nind = min(bisect.bisect_left(xcord, xcord[s] + k + 1), n - 1)
		ov = min(bisect.bisect_left(xcord, xcord[s] + k + 1), n - 1)
		if xcord[ov] > xcord[s] + k:
			ov -= 1
		p2 = maxsofar[nind]
		if nind <= ov:
			overlap = nind + 1 - ov
			ans = p1 + p2 - overlap
		else:
			ans = p1 + p2
		maxans = max(maxans, ans)
	print(maxans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	plat1 = [0] * n
	plat2 = [0] * n
	p_left = 0
	for i in range(n):
		if x[i] > x[p_left] + k:
			p_left += 1
		plat1[i] = i - p_left + 1
		if i > 0:
			plat1[i] = max(plat1[i - 1], plat1[i])
	p_right = n - 1
	for i in range(n - 1, -1, -1):
		if x[i] < x[p_right] - k:
			p_right -= 1
		plat2[i] = p_right - i + 1
		if i < n - 1:
			plat2[i] = max(plat2[i + 1], plat2[i])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, plat1[i] + plat2[i + 1])
	print(ans)


import sys
from collections import defaultdict as dd
from collections import deque
from functools import *
from fractions import Fraction as f
from copy import *
from bisect import *
from heapq import *
from math import *
from itertools import permutations, product

def eprint(*args):
	print(*args, file=sys.stderr)
zz = 1
if zz:
	input = sys.stdin.readline
else:
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('all.txt', 'w')

def inc(d, c):
	d[c] = d[c] + 1 if c in d else 1

def bo(i):
	return ord(i) - ord('A')

def li():
	return [int(xx) for xx in input().split()]

def fli():
	return [float(x) for x in input().split()]

def comp(a, b):
	if a > b:
		return 2
	return 2 if a == b else 0

def gi():
	return [xx for xx in input().split()]

def fi():
	return int(input())

def pro(a):
	return reduce(lambda a, b: a * b, a)

def swap(a, i, j):
	(a[i], a[j]) = (a[j], a[i])

def si():
	return list(input().rstrip())

def mi():
	return map(int, input().split())

def gh():
	sys.stdout.flush()

def isvalid(i, j):
	return 0 <= i < n and 0 <= j < n

def bo(i):
	return ord(i) - ord('a')

def graph(n, m):
	for i in range(m):
		(x, y) = mi()
		a[x].append(y)
		a[y].append(x)
t = fi()

def sod(n):
	p = str(n)
	c = 0
	for i in range(len(p)):
		c += int(p[i])
	return c
while t > 0:
	t -= 1
	(n, k) = mi()
	a = li()
	y = li()
	a.sort()
	d = [0] * (n + 1)
	r = [0] * (n + 1)
	for i in range(n):
		p = bisect_left(a, a[i] + k + 1)
		r[i] = p
		d[i] = p - i
	suf = [0] * (n + 1)
	for i in range(n - 1, -1, -1):
		suf[i] = max(suf[i + 1], d[i])
	maxi = 0
	for i in range(n):
		maxi = max(maxi, d[i] + suf[r[i]])
	print(maxi)


from bisect import *
T = int(input())
ans = [0] * T
for t in range(T):
	(n, k) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	X.sort()
	plat = [0] * n
	for i in range(n):
		plat[i] = bisect_right(X, X[i] + k) - i
	max_lis = [plat[-1]] * n
	for i in range(n - 2, -1, -1):
		max_lis[i] = max(plat[i], max_lis[i + 1])
	for i in range(n):
		if plat[i] + i == n:
			ans[t] = max(ans[t], n - i)
			break
		ans[t] = max(ans[t], plat[i] + max_lis[plat[i] + i])
print(*ans, sep='\n')


tc = int(input())
for _ in range(tc):
	(n, k) = map(int, input().split(' '))
	x = sorted(list(map(int, input().split(' '))))
	input()
	left = [1] * n
	l = 0
	for r in range(1, n):
		while x[r] - x[l] > k:
			l += 1
		left[r] = r - l + 1
		left[r] = max(left[r], left[r - 1])
	right = [1] * n
	r = n - 1
	for l in reversed(range(n - 1)):
		while x[r] - x[l] > k:
			r -= 1
		right[l] = r - l + 1
		right[l] = max(right[l], right[l + 1])
	answer = 1
	for i in range(n - 1):
		answer = max(answer, left[i] + right[i + 1])
	print(answer)


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	xcor = list(map(int, input().split()))
	ycor = list(map(int, input().split()))
	arr = []
	for i in range(n):
		arr.append([xcor[i], ycor[i]])
	arr.sort()
	dp = [0 for i in range(n)]
	dp[n - 1] = 1
	for i in range(n - 2, -1, -1):
		dp[i] = dp[i + 1]
		lo = i
		hi = n - 1
		e = 0
		while lo <= hi:
			mid = (lo + hi) // 2
			if arr[mid][0] <= arr[i][0] + k:
				e = mid - i + 1
				lo = mid + 1
			else:
				hi = mid - 1
		dp[i] = max(dp[i], e)
	ans = 0
	for i in range(n):
		lo = i
		hi = n - 1
		pos = i
		while lo <= hi:
			mid = (lo + hi) // 2
			if arr[mid][0] <= arr[i][0] + k:
				pos = mid
				lo = mid + 1
			else:
				hi = mid - 1
		me = pos - i + 1
		if pos + 1 < n:
			me += dp[pos + 1]
		ans = max(ans, me)
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = map(int, input().split())
	x.sort()
	start = 0
	p = [0] * n
	p[0] = 1
	for i in range(1, n):
		if x[i] - x[start] <= k:
			p[i] = i - start + 1
		else:
			while x[i] - x[start] > k:
				start += 1
			p[i] = i - start + 1
	last = n - 1
	s = [0] * n
	s[-1] = 1
	for i in range(len(s) - 2, -1, -1):
		if x[last] - x[i] <= k:
			s[i] = last - i + 1
		else:
			while x[last] - x[i] > k:
				last -= 1
			s[i] = last - i + 1
	for i in range(1, n):
		p[i] = max(p[i], p[i - 1], 0)
	mx = p[0]
	for i in range(n - 1):
		mx = max(mx, p[i] + s[i + 1])
	print(max(mx, max(p), max(s)))


import bisect
T = int(input())
r = 1
while r <= T:
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x = sorted(x)
	if x[-1] - x[0] <= 2 * k + 1:
		print(n)
		r += 1
		continue
	cur = [0] * n
	for i in range(n):
		cur[i] = bisect.bisect(x, x[i] + k) - bisect.bisect_left(x, x[i])
	maxcur = [0] * n
	maxcur[-1] = cur[-1]
	for i in range(n - 2, -1, -1):
		maxcur[i] = max(cur[i], maxcur[i + 1])
	ans = 0
	for i in range(n):
		if bisect.bisect(x, x[i] + k) < n:
			ans = max(ans, cur[i] + maxcur[bisect.bisect(x, x[i] + k)])
	print(ans)
	r += 1


def solution(n, k, x, y):
	x.sort()
	(l, r, a, b, c) = ([], [], 0, 0, 1)
	while b < n:
		if c <= n - 1:
			while x[c] - x[b] <= k:
				c += 1
				if c == n:
					break
		while x[b] - x[a] > k:
			a += 1
		r.append(c - b)
		l.append(b - a + 1)
		b += 1
	for i in range(1, n):
		l[i] = max(l[i - 1], l[i])
		r[n - 1 - i] = max(r[n - 1 - i], r[n - i])
	max_ = l[0]
	for i in range(n - 1):
		max_ = max(max_, l[i] + r[i + 1])
	return max_
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split(' '))
	x = list(map(int, input().split(' ')))
	y = list(map(int, input().split(' ')))
	print(solution(n, k, x, y))


import sys, itertools, collections, bisect
from collections import deque, Counter, defaultdict
from heapq import heappush, heappop, heapify
read = sys.stdin.readline
sys.setrecursionlimit(10 ** 6)

def solve():
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	L = [0] * n
	for i in range(n):
		j = bisect.bisect_left(x, x[i] + k + 1)
		L[i] = j - i
	R = [0] * n
	R[-1] = L[-1]
	for i in reversed(range(n - 1)):
		R[i] = max(L[i], R[i + 1])
	ans = 0
	for i in range(n):
		if i + L[i] < n:
			ans = max(ans, L[i] + R[i + L[i]])
		else:
			ans = max(ans, L[i])
	print(ans)
t = int(input())
for _ in range(t):
	solve()


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))
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	xs = list(map(int, input().split()))
	ys = list(map(int, input().split()))
	s = SortedList(xs)
	saved = [None] * n
	for (i, x) in enumerate(s):
		saved[i] = s.bisect_right(x + k) - s.bisect_left(x)
	base = 1
	while base < n:
		base *= 2
	tree = [0] * base + saved + [0] * (base - n)
	for i in range(base - 1, 0, -1):
		tree[i] = max(tree[2 * i], tree[2 * i + 1])

	def query(a, b):
		a += base
		b += base
		m = 0
		while a < b:
			if a % 2 == 1:
				m = max(m, tree[a])
				a += 1
			if b % 2 == 1:
				m = max(m, tree[b - 1])
				b -= 1
			a //= 2
			b //= 2
		return m
	m = 0
	for i in range(n):
		m = max(m, saved[i] + query(i + saved[i], n))
	print(m)


import bisect

def calc(n, k, a):
	front = [0 for i in range(n)]
	back = [0 for i in range(n)]
	ans = 0
	a.sort()
	front[0] = 1
	for i in range(1, n):
		idx = bisect.bisect_left(a, a[i] - k, 0, i)
		front[i] = max(i - idx + 1, front[i - 1])
	back[n - 1] = 0
	for i in range(n - 2, -1, -1):
		idx = bisect.bisect(a, a[i + 1] + k, i + 1, n - 1)
		curr = idx - (i + 1) + 1
		if a[idx] > a[i + 1] + k:
			curr -= 1
		back[i] = max(back[i + 1], curr)
	for i in range(n):
		ans = max(ans, front[i] + back[i])
	return min(ans, n)
t = int(input())
for i in range(t):
	(n, k) = list(map(int, input().split()))
	ax = list(map(int, input().split()))
	ay = list(map(int, input().split()))
	print(calc(n, k, ax))


from sys import stdin, stdout

def find(N, K, X):
	X.sort()
	arrA = [0]
	j = 0
	r = 0
	for i in range(N):
		r += 1
		if i < N - 1 and X[i] == X[i + 1]:
			continue
		while X[i] - X[j] > K:
			j += 1
			r -= 1
		arrA.append(r)
	X.reverse()
	arrB = [0]
	j = 0
	r = 0
	for i in range(N):
		r += 1
		if i < N - 1 and X[i] == X[i + 1]:
			continue
		while -X[i] + X[j] > K:
			j += 1
			r -= 1
		arrB.append(r)
	for i in range(1, len(arrA)):
		arrA[i] = max(arrA[i], arrA[i - 1])
		arrB[i] = max(arrB[i], arrB[i - 1])
	arrB.reverse()
	return max([arrA[i] + arrB[i] for i in range(len(arrA))])

def main():
	for _ in range(int(stdin.readline())):
		(N, K) = list(map(int, stdin.readline().split()))
		X = list(map(int, stdin.readline().split()))
		list(map(int, stdin.readline().split()))
		print(find(N, K, X))
main()


import array
import bisect
import math
import os
import random
import re
import sys
from typing import List, Any
sys.setrecursionlimit(10000)
ACODE = ord('a')
INIT = -1
INF = 10 ** 9
n: int
k: int
dp: List[Any]
X: List[int]
Y: List[int]

def printf(format, *args):
	sys.stdout.write(format % args)

def solve() -> int:
	global n, k, dp
	ans = 0
	for i in range(n):
		j = bisect.bisect_right(X, X[i] + k)
		t = j - i
		dp[j] = max(dp[j], t)
		ans = max(ans, dp[j])
	for i in range(1, n):
		dp[i] = max(dp[i], dp[i - 1])
		j = bisect.bisect_right(X, X[i] + k)
		t = j - i
		ans = max(ans, dp[i] + t)
	return ans

def main():
	global n, k, X, Y, dp
	tc = int(input().strip())
	for _ in range(tc):
		[n, k] = list(map(int, input().strip().split(' ')))
		X = list(map(int, input().strip().split(' ')))
		Y = list(map(int, input().strip().split(' ')))
		X.sort()
		dp = array.array('q', [0]) * (n + 1)
		print(solve())
main()


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	if n <= 2:
		print(n)
		continue
	l = [0] * n
	j = 0
	for i in range(n):
		while x[i] - x[j] > k:
			j += 1
		l[i] = i - j + 1
		if i > 0:
			l[i] = max(l[i], l[i - 1])
	j = n - 1
	r = [0] * n
	for i in range(n - 1, -1, -1):
		while x[j] - x[i] > k:
			j -= 1
		r[i] = j - i + 1
		if i < n - 1:
			r[i] = max(r[i], r[i + 1])
	c = 2
	for i in range(n - 1):
		c = max(c, l[i] + r[i + 1])
	print(c)


import sys
import math
import bisect
from sys import stdin, stdout
from math import gcd, floor, sqrt, log2, ceil, pi, sin, cos, acos, atan
from collections import defaultdict as dd
from bisect import bisect_left as bl, bisect_right as br
from bisect import insort
from collections import Counter
from collections import deque
from heapq import heappush, heappop, heapify
from itertools import permutations, combinations
mod = int(1000000000.0) + 7
ip = lambda : int(stdin.readline())
inp = lambda : map(int, stdin.readline().split())
ips = lambda : stdin.readline().rstrip()
out = lambda x: stdout.write(str(x) + '\n')
t = ip()
for _ in range(t):
	(n, k) = inp()
	xx = list(inp())
	yy = list(inp())
	dic = dd(int)
	for i in xx:
		dic[i] += 1
	ch = sorted(list(dic.keys()))
	n = len(ch)
	start = [0] * n
	end = [0] * n
	stack = deque()
	val = 0
	for i in range(n):
		if len(stack) == 0:
			stack.append(ch[i])
			val += dic[ch[i]]
		else:
			stack.append(ch[i])
			val += dic[ch[i]]
			while True:
				if stack[-1] - stack[0] > k:
					ele = stack.popleft()
					val -= dic[ele]
				else:
					break
		if i == 0:
			start[i] = val
		else:
			start[i] = max(start[i - 1], val)
	stack = deque()
	val = 0
	for j in range(n - 1, -1, -1):
		if j == n - 1:
			continue
		else:
			i = j + 1
		if len(stack) == 0:
			stack.append(ch[i])
			val += dic[ch[i]]
		else:
			stack.append(ch[i])
			val += dic[ch[i]]
			while True:
				if stack[0] - stack[-1] > k:
					ele = stack.popleft()
					val -= dic[ele]
				else:
					break
		end[j] = max(val, end[j + 1])
	ans = -float('inf')
	for i in range(n):
		ans = max(ans, start[i] + end[i])
	out(ans)


import collections
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	best_st = [0, 0]
	ans = 0
	queue = collections.deque()
	x.sort()
	for i in range(len(x)):
		while len(queue) and x[i] - queue[0] > k:
			queue.popleft()
		queue.append(x[i])
		best_st[-1] = max(best_st[-1], len(queue))
		best_st.append(best_st[-1])
	t = 0
	queue = collections.deque()
	for i in range(len(x)):
		while len(queue) and x[i] - queue[0] > k:
			queue.popleft()
		queue.append(x[i])
		while t < len(x) - 1 and x[t] < queue[0]:
			t += 1
		ans = max(len(queue) + best_st[t], ans)
	print(ans)


from bisect import bisect_right
import sys
input = sys.stdin.buffer.readline

def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		xlst = list(map(int, input().split()))
		_ = input()
		xlst.sort()
		cnt = []
		xlst.append(10 ** 15)
		r = 0
		for (i, x) in enumerate(xlst[:-1]):
			while xlst[r] <= x + k:
				r += 1
			cnt.append(r - i)
		max_cnt = 0
		mc_lst = []
		for c in cnt[::-1]:
			max_cnt = max(max_cnt, c)
			mc_lst.append(max_cnt)
		mc_lst = mc_lst[::-1]
		mc_lst.append(0)
		ans = 0
		for (i, x) in enumerate(xlst[:-1]):
			pos = bisect_right(xlst, x + k)
			ans = max(ans, cnt[i] + mc_lst[pos])
		print(ans)
main()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	l = [1]
	r = [1]
	left = 0
	right = n - 1
	for pos in range(1, n):
		while x[left] < x[pos] - k:
			left += 1
		l.append(max(l[-1], pos - left + 1))
	pos = 0
	for pos in range(n - 2, -1, -1):
		while x[right] > x[pos] + k:
			right -= 1
		r.append(max(r[-1], right - pos + 1))
	r.reverse()
	ans = 1
	for i in range(n - 1):
		ans = max(l[i] + r[i + 1], ans)
	print(ans)


import sys
import math
from bisect import bisect_right

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

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

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

def SI():
	return sys.stdin.readline().strip()
t = II()
for q in range(t):
	(n, k) = MI()

	def bs(a, x):
		i = bisect_right(a, x)
		return max(i - 1, 0)
	x = sorted(LI())
	y = LI()
	d = [0] * n
	for i in range(n):
		ind = bs(x, x[i] + k)
		d[i] = ind - i + 1
	mm = [0] * n
	ma = 0
	for i in range(n - 1, -1, -1):
		ma = max(ma, d[i])
		mm[i] = ma
	m = 0
	for i in range(n):
		ind = bs(x, x[i] + k)
		if ind == n - 1:
			s = 0
		else:
			s = mm[ind + 1]
		m = max(m, d[i] + s)
	print(m)


import math
import bisect
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = []
	arr = list(map(int, input().split()))
	mk = list(map(int, input().split()))
	arr.sort()
	l = []
	xx = []
	for i in range(n):
		bi = bisect.bisect(arr, arr[i] + k)
		l.append([i, bi])
		xx.append(bi - i)
	l.sort(key=lambda x: -x[1] + x[0])
	for i in range(n - 2, -1, -1):
		xx[i] = max(xx[i], xx[i + 1])
	xx = xx + [0]
	ma = 0
	for i in l:
		ma = max(ma, i[1] - i[0] + xx[i[1]])
	print(ma)


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import *
from copy import *
from collections import deque
from collections import Counter as counter
from itertools import combinations as comb
from itertools import permutations as permutate
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
mod = 1000000007

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

def solve(case):
	(n, k) = sep()
	x = lis()
	y = lis()
	x = sorted(x)
	right = [0] * (n + 1)
	left = [0] * (n + 1)
	ind = 0
	for i in range(n):
		while x[i] - x[ind] > k:
			ind += 1
		left[i] = max(i - ind + 1, left[i - 1])
	ind = n - 1
	for i in range(n - 1, -1, -1):
		while x[ind] - x[i] > k:
			ind -= 1
		right[i] = max(ind - i + 1, right[i + 1])
	ans = 0
	for i in range(n):
		ans = max(ans, left[i] + right[i + 1])
	print(ans)
testcase(int(inp()))


import sys
import bisect
import math as mt
input = sys.stdin.readline
t = int(input())
mod = 10 ** 9 + 7
for _ in range(t):
	(n, k) = map(int, input().split())
	l1 = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	l1.sort()
	(ans, ans2, ans1) = (0, 0, 0)
	pref = [0] * (n + 1)
	for i in range(n):
		pos = bisect.bisect_right(l1, l1[i] + k)
		pref[i] = pos - i
	maxi = pref[-1]
	for i in range(n - 1, -1, -1):
		maxi = max(maxi, pref[i])
		pref[i] = max(maxi, pref[-1])
	for i in range(n):
		ans1 = 0
		pos = bisect.bisect_right(l1, l1[i] + k)
		ans1 = pos - i
		if pos < n:
			ans = max(ans1 + pref[pos], ans)
		else:
			ans = max(ans, ans1)
	print(ans)


import sys, bisect
input = sys.stdin.readline
T = int(input())
for _ in range(T):
	(n, k) = map(int, input().split())
	A = list(map(int, input().split()))
	B = list(map(int, input().split()))
	V = []
	A.sort()
	for i in range(n):
		val = A[i] + k
		v = bisect.bisect(A, val)
		V.append(v - i)
	MV = []
	v = V[n - 1]
	for i in range(n - 1, -1, -1):
		v = max(v, V[i])
		MV.append(v)
	MV = MV[::-1]
	ans = min(n, 2)
	for i in range(n):
		v = V[i]
		if i + v <= n - 1:
			ans = max(ans, v + MV[i + v])
		else:
			ans = max(ans, V[i])
	print(ans)


def solve(coords, k):
	left = 0
	right = 0
	dp = [0]
	result = 0
	while True:
		while right < len(coords) and coords[right] - coords[left] <= k:
			right += 1
			dp.append(max(dp[right - 1], right - left))
		result = max(result, dp[left] + right - left)
		if right == len(coords):
			break
		left += 1
	return result
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	coords = sorted(map(int, input().split()))
	input()
	print(solve(coords, k))


import sys
INF = 10 ** 20
MOD = 10 ** 9 + 7
I = lambda : list(map(int, input().split()))
from math import gcd
from math import ceil
from collections import defaultdict as dd, Counter
from bisect import bisect_left as bl, bisect_right as br

def solve():
	(n, k) = I()
	a = I()
	y = I()
	a.sort()
	max_till = [0] * (2 * n)
	ans = 0
	for i in range(n - 1, -1, -1):
		(left, right) = (a[i], a[i] + k)
		idxR = br(a, right)
		idxL = bl(a, left)
		cur = idxR - idxL
		max_till[i] = max(max_till[i + 1], cur)
		ans = max(ans, cur + max_till[idxR])
	print(ans)
(t,) = I()
while t:
	t -= 1
	solve()


import os
from heapq import heapify, heappop, heappush
import sys
import math
import operator
from bisect import bisect_right
from collections import defaultdict
from io import BytesIO, IOBase
sys.setrecursionlimit(10 ** 5)

def inpt():
	return [int(k) for k in input().split()]

def main():
	for _ in range(int(input())):
		(n, k) = inpt()
		X = inpt()
		Y = inpt()
		X.sort()
		ct = 0
		pref = []
		for i in range(n):
			ct += 1
			pref.append(ct)
		ar = []
		mx = 0
		br = []
		for i in range(n):
			pos = bisect_right(X, X[i] + k) - 1
			val = pref[pos]
			if i != 0:
				val -= pref[i - 1]
			mx = max(mx, val)
			br.append(val)
			ar.append(mx)
		ans = 0
		mx = 0
		for i in range(n - 1, -1, -1):
			mx = max(br[i], mx)
			br[i] = mx
		for i in range(n):
			pos = bisect_right(X, X[i] + k)
			temp = ar[i]
			if pos < n:
				temp += br[pos]
			ans = max(ans, temp)
		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()


import sys
input = sys.stdin.readline
from collections import *
from bisect import *
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	cnt = Counter(x)
	x = list(set(x))
	x.sort()
	acc = [0]
	for xi in x:
		acc.append(acc[-1] + cnt[xi])
	r = [-1] * len(x)
	score = []
	for i in range(len(x)):
		j = bisect_right(x, x[i] + k)
		r[i] = j
		score.append(acc[j] - acc[i])
	score.append(0)
	ans = 0
	for i in range(len(x) - 1, -1, -1):
		ans = max(ans, score[i] + score[r[i]])
		score[i] = max(score[i], score[i + 1])
	print(ans)


for _ in range(int(input())):
	(n, p) = [int(x) for x in input().split()]
	a = [int(x) for x in input().split()]
	b = input()
	a.sort()
	b = []
	c = []
	j = 0
	k = 0
	if n <= 2:
		print(n)
		continue
	for i in range(n):
		while a[i] - a[j] > p:
			j += 1
		while k < n and a[k] - a[i] <= p:
			k += 1
		k -= 1
		b.append(i - j + 1)
		c.append(k - i + 1)
	for i in range(1, n - 1):
		b[i] = max(b[i], b[i - 1])
		c[n - i - 1] = max(c[n - i - 1], c[n - i])
	ss = 0
	for i in range(n - 1):
		ss = max(ss, b[i] + c[i + 1])
	print(ss)


t = int(input())
while t > 0:
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	prefix = [0] * (n + 2)
	suffix = [0] * (n + 2)
	i = 1
	j = 1
	while i <= n and j <= n:
		diff = x[j - 1] - x[i - 1]
		if diff <= k:
			prefix[j] = max(j - i + 1, prefix[j - 1])
			j += 1
		else:
			i += 1
	i = n
	j = n
	while i >= 0 and j >= 0:
		diff = abs(x[j - 1] - x[i - 1])
		if diff <= k:
			suffix[i] = max(abs(j - i + 1), suffix[i + 1])
			i -= 1
		else:
			j -= 1
	max_points = 0
	for i in range(1, n + 1):
		max_points = max(max_points, prefix[i] + suffix[i + 1])
	print(max_points)
	t -= 1


import sys, bisect, string, math, time, functools, random, fractions
from heapq import heappush, heappop, heapify
from collections import deque, defaultdict, Counter
from itertools import permutations, combinations, groupby
rep = range
R = range

def Golf():
	(n, *t) = map(int, open(0).read().split())

def I():
	return int(input())

def S_():
	return input()

def IS():
	return input().split()

def LS():
	return [i for i in input().split()]

def MI():
	return map(int, input().split())

def LI():
	return [int(i) for i in input().split()]

def LI_():
	return [int(i) - 1 for i in input().split()]

def NI(n):
	return [int(input()) for i in range(n)]

def NI_(n):
	return [int(input()) - 1 for i in range(n)]

def NLI(n):
	return [[int(i) for i in input().split()] for i in range(n)]

def NLI_(n):
	return [[int(i) - 1 for i in input().split()] for i in range(n)]

def StoLI():
	return [ord(i) - 97 for i in input()]

def ItoS(n):
	return chr(n + 97)

def LtoS(ls):
	return ''.join([chr(i + 97) for i in ls])

def RA():
	return map(int, open(0).read().split())

def RLI(n=8, a=1, b=10):
	return [random.randint(a, b) for i in range(n)]

def RI(a=1, b=10):
	return random.randint(a, b)

def Rtest(T):
	(case, err) = (0, 0)
	for i in range(T):
		inp = INP()
		(a1, ls) = naive(*inp)
		a2 = solve(*inp)
		if a1 != a2:
			print((a1, a2), inp)
			err += 1
		case += 1
	print('Tested', case, 'case with', err, 'errors')

def GI(V, E, ls=None, Directed=False, index=1):
	org_inp = []
	g = [[] for i in range(V)]
	FromStdin = True if ls == None else False
	for i in range(E):
		if FromStdin:
			inp = LI()
			org_inp.append(inp)
		else:
			inp = ls[i]
		if len(inp) == 2:
			(a, b) = inp
			c = 1
		else:
			(a, b, c) = inp
		if index == 1:
			a -= 1
			b -= 1
		aa = (a, c)
		bb = (b, c)
		g[a].append(bb)
		if not Directed:
			g[b].append(aa)
	return (g, org_inp)

def GGI(h, w, search=None, replacement_of_found='.', mp_def={'#': 1, '.': 0}, boundary=1):
	mp = [boundary] * (w + 2)
	found = {}
	for i in R(h):
		s = input()
		for char in search:
			if char in s:
				found[char] = (i + 1) * (w + 2) + s.index(char) + 1
				mp_def[char] = mp_def[replacement_of_found]
		mp += [boundary] + [mp_def[j] for j in s] + [boundary]
	mp += [boundary] * (w + 2)
	return (h + 2, w + 2, mp, found)

def TI(n):
	return GI(n, n - 1)

def accum(ls):
	rt = [0]
	for i in ls:
		rt += [rt[-1] + i]
	return rt

def bit_combination(n, base=2):
	rt = []
	for tb in R(base ** n):
		s = [tb // base ** bt % base for bt in R(n)]
		rt += [s]
	return rt

def gcd(x, y):
	if y == 0:
		return x
	if x % y == 0:
		return y
	while x % y != 0:
		(x, y) = (y, x % y)
	return y

def YN(x):
	print(['NO', 'YES'][x])

def Yn(x):
	print(['No', 'Yes'][x])

def show(*inp, end='\n'):
	if show_flg:
		print(*inp, end=end)
mo = 10 ** 9 + 7
inf = float('inf')
FourNb = [(-1, 0), (1, 0), (0, 1), (0, -1)]
EightNb = [(-1, 0), (1, 0), (0, 1), (0, -1), (1, 1), (-1, -1), (1, -1), (-1, 1)]
compas = dict(zip('WENS', FourNb))
cursol = dict(zip('LRUD', FourNb))
l_alp = string.ascii_lowercase
read = sys.stdin.buffer.read
readline = sys.stdin.buffer.readline
input = lambda : sys.stdin.readline().rstrip()
show_flg = False
show_flg = True
ans = 0
for _ in range(I()):
	(n, k) = LI()
	x = sorted(LI())
	LI()
	ans = 0
	ans = sorted(x)
	ar = [bisect.bisect(x, x[i] + k) - i for i in range(n)]
	al = [(x[i], i, bisect.bisect(x, x[i] - 2)) for i in range(n)]
	al = [i - bisect.bisect(x, x[i] - k - 1) + 1 for i in range(n)]
	(lmax, rmax) = ([0], [0])
	for i in range(n):
		rmax += (max(rmax[-1], ar[n - i - 1]),)
	rmax = rmax[-1:0:-1]
	lmax = [0]
	for i in range(n):
		lmax += (max(lmax[-1], al[i]),)
	lmax = lmax[1:]
	ans = rmax[0]
	for i in range(n):
		if i + ar[i] < n:
			ans = max(ans, ar[i] + rmax[i + ar[i]])
	print(ans)


def main():
	t = eval(input())
	for cas in range(t):
		(n, k) = map(int, input().split())
		x = list(map(int, input().split()))
		y = list(map(int, input().split()))
		x.sort()
		r = [0 for _ in range(n + 5)]
		l = [0 for _ in range(n + 5)]
		tmp = 0
		for i in range(n):
			while x[i] - x[tmp] > k:
				tmp += 1
			l[i] = i - tmp + 1
			if i > 0:
				l[i] = max(l[i], l[i - 1])
		tmp = n - 1
		for i in range(n - 1, -1, -1):
			while x[tmp] - x[i] > k:
				tmp -= 1
			r[i] = tmp - i + 1
			if i + 1 < n:
				r[i] = max(r[i], r[i + 1])
		ret = 1
		for i in range(n - 1):
			ret = max(ret, r[i + 1] + l[i])
		print(ret)
main()


import bisect

def solve(arr, n, k):
	arr.sort()
	endIndex = [bisect.bisect(arr, arr[i] + k) for i in range(n)]
	maxLength = [None] * n
	currMax = -1
	for i in range(n - 1, -1, -1):
		length = endIndex[i] - i
		if length > currMax:
			maxLength[i] = length
			currMax = length
		else:
			maxLength[i] = currMax
	ans = -1
	for i in range(n):
		end = endIndex[i]
		if end == n:
			ans = max(ans, end - i)
		else:
			ans = max(ans, end - i + maxLength[end])
	return ans
t = int(input())
for _ in range(t):
	(n, k) = [*map(int, input().split())][:2]
	x = [*map(int, input().split())]
	y = [*map(int, input().split())]
	print(solve(x, n, k))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = input()
	x.sort()
	L = [0 for _ in range(n)]
	R = [0 for _ in range(n)]
	prev = 0
	L[0] = 1
	for i in range(1, n):
		L[i] = L[i - 1] + 1
		while x[i] - x[prev] > k:
			prev += 1
			L[i] -= 1
	prev = n - 1
	R[prev] = 1
	for i in range(n - 2, -1, -1):
		R[i] = R[i + 1] + 1
		while x[prev] - x[i] > k:
			prev -= 1
			R[i] -= 1
	for i in range(1, n):
		L[i] = max(L[i], L[i - 1])
	for i in range(n - 2, -1, -1):
		R[i] = max(R[i], R[i + 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, R[i + 1] + L[i])
	print(ans)


import heapq as h

def get_max_ind(X, max_val, N):
	left = 0
	right = N - 1
	if X[right] <= max_val:
		return right
	while right - left > 1:
		middle = (left + right) // 2
		if X[middle] <= max_val:
			left = middle
		else:
			right = middle
	return left

def solve(N, K, X):
	X.sort()
	longest_starting_at = []
	for i in range(N):
		start = X[i]
		max_val = X[i] + K
		max_ind = get_max_ind(X, max_val, N)
		longest_starting_at.append((max_ind - i + 1, max_ind))
	longest_to_right = []
	best = 0
	for i in range(N - 1, -1, -1):
		curr = longest_starting_at[i][0]
		longest_to_right.append(max(curr, best))
		best = max(curr, best)
	longest_to_right.reverse()
	ans = 0
	for i in range(N):
		tmp_ans = longest_starting_at[i][0]
		max_ind = longest_starting_at[i][1]
		if max_ind < N - 1:
			tmp_ans += longest_to_right[max_ind + 1]
		ans = max(ans, tmp_ans)
	return ans
T = int(input())
for t in range(1, T + 1):
	(N, K) = [int(s) for s in input().split()]
	X = [int(s) for s in input().split()]
	Y = [int(s) for s in input().split()]
	print(solve(N, K, X))


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	cnt = {}
	for i in x:
		cnt[i] = 0
	for i in x:
		cnt[i] += 1
	(keys, first, last, val) = (list(cnt.keys()), {}, {}, 0)
	for i in keys:
		(first[i], last[i]) = (0, 0)
	keys.sort()
	(i, j) = (0, 0)
	while i < len(keys) or j < len(keys):
		if j < len(keys) and keys[j] <= keys[i] + k:
			val += cnt[keys[j]]
			if i < len(keys):
				first[keys[i]] = max(first[keys[i]], val)
			if j < len(keys):
				last[keys[j]] = max(last[keys[j]], val)
			j += 1
		else:
			val -= cnt[keys[i]]
			i += 1
			if i < len(keys):
				first[keys[i]] = max(first[keys[i]], val)
			if j < len(keys):
				last[keys[j]] = max(last[keys[j]], val)
	(mx, res) = (0, first[keys[0]])
	for i in range(1, len(keys)):
		mx = max(mx, last[keys[i - 1]])
		res = max(res, mx + first[keys[i]])
	print(res)


def solve():
	(n, k) = map(int, input().split())
	a = [int(i) for i in input().split()]
	input()
	dp = [0] * (n + 10)
	ma = [0] * (n + 10)
	r = -1
	a.sort()
	for i in range(n):
		r = max(r, i)
		for j in range(r, n):
			if a[j] <= a[i] + k:
				r = j
			else:
				break
		dp[i] = r - i + 1
	for i in range(n, -1, -1):
		ma[i] = max(dp[i], ma[i + 1])
	ans = 0
	for i in range(n):
		ans = max(dp[i] + ma[i + dp[i]], ans)
	print(ans)
t = int(input())
for i in range(t):
	solve()


import sys, threading
from collections import defaultdict, Counter
input = sys.stdin.readline

def rl(type):
	return [type(w) for w in input().split()]

def reverse(arr):
	return arr[-1::-1]

def mod(a, m):
	return (a % m + m) % m

def create_graph(n):
	graph = {}
	for _ in range(n):
		(x, y) = map(int, input().split())
		graph[x].append(y)
		graph[y].append(x)
	return graph

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		arr = rl(int)
		_ = rl(int)
		arr.sort()
		prefix = [0] * n
		suffix = [0] * n
		j = 0
		for i in range(n):
			while arr[i] - arr[j] > k:
				j += 1
			prefix[i] = i - j + 1
			if i > 0:
				prefix[i] = max(prefix[i], prefix[i - 1])
		j = n - 1
		for i in range(n - 1, -1, -1):
			while arr[j] - arr[i] > k:
				j -= 1
			suffix[i] = j - i + 1
			if i < n - 1:
				suffix[i] = max(suffix[i], suffix[i + 1])
		result = 1
		for i in range(n - 1):
			result = max(result, prefix[i] + suffix[i + 1])
		print(result)
sys.setrecursionlimit(10 ** 6)
threading.stack_size(10 ** 8)
t = threading.Thread(target=main)
t.start()
t.join()


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	a.sort()
	(ret, ret2) = (1, 0)
	(j, l) = (1, 0)
	for i in range(1, n):
		while a[i] - a[j] > k:
			j += 1
			while a[j - 1] - a[l] > k:
				l += 1
			ret2 = max(ret2, j - l)
		ret2 = max(ret2, j - l)
		ret = max(ret, i - j + 1 + ret2)
	print(ret)


def ans(n, k, x, y):
	x.sort()
	l = [0] * len(x)
	r = [0] * len(x)
	i = 0
	j = 0
	temp = 0
	while i < len(x) and j < len(x):
		temp = i - j + 1
		if i == j:
			l[i] = temp
			i += 1
		elif x[i] - x[j] <= k:
			l[i] = temp
			i += 1
		else:
			j += 1
	i = n - 1
	j = n - 1
	temp = 0
	while i >= 0 and j >= 0:
		temp = j - i + 1
		if i == j:
			r[i] = temp
			i -= 1
		elif x[j] - x[i] <= k:
			r[i] = temp
			i -= 1
		else:
			j -= 1
	prefix = [0] * len(x)
	suffix = [0] * len(x)
	prefix[0] = l[0]
	suffix[-1] = r[-1]
	for i in range(1, len(x)):
		prefix[i] = max(l[i], prefix[i - 1])
	for i in range(len(x) - 2, -1, -1):
		suffix[i] = max(r[i], suffix[i + 1])
	answer = 1
	for i in range(n - 1):
		answer = max(answer, prefix[i] + suffix[i + 1])
	print(answer)
m = int(input())
for i in range(m):
	arr = input().split()
	n = int(arr[0])
	k = int(arr[1])
	a = input().split()
	b = input().split()
	x = []
	y = []
	for j in a:
		x.append(int(j))
	for j in b:
		y.append(int(j))
	ans(n, k, x, y)


from bisect import bisect_left, bisect_right
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	(*x,) = map(int, input().split())
	(*y,) = map(int, input().split())
	x = sorted(x)
	counti = []
	countmax = [0]
	ans = 0
	for i in range(n):
		l = bisect_left(x, x[i])
		r = bisect_right(x, x[i] + k)
		counti.append(r - l)
		countmax.append(max(r - l, countmax[-1]))
		ind = bisect_left(x, x[i] - k)
		ans = max(ans, r - l + countmax[ind])
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = sorted(map(int, input().split()))
	input()
	j = n - 1
	r = [-1] * n
	l = [-1] * n
	for i in range(n - 1, -1, -1):
		if x[j] - x[i] > k:
			j = j - 1
		r[i] = j - i + 1
		if i < n - 1:
			r[i] = max(r[i], r[i + 1])
	j = 0
	for i in range(0, n, 1):
		if x[i] - x[j] > k:
			j = j + 1
		l[i] = i - j + 1
		if i > 0:
			l[i] = max(l[i], l[i - 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, l[i] + r[i + 1])
	print(ans)


h = int(input())
l = []
for i in range(h):
	(n, k) = list(map(int, input().split()))
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	a = [None] * n
	b = [None] * n
	x.sort()
	j = n - 1
	for h in range(n - 1, -1, -1):
		while x[j] - x[h] > k:
			j -= 1
		a[h] = j - h + 1
		if h + 1 < n:
			a[h] = max(a[h], a[h + 1])
	j = 0
	for h in range(n):
		while x[h] - x[j] > k:
			j += 1
		b[h] = h - j + 1
		if h > 0:
			b[h] = max(b[h], b[h - 1])
	ans = 1
	for h in range(n - 1):
		ans = max(ans, a[h + 1] + b[h])
	print(ans)


import sys
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline

def main():
	t = int(input())
	import bisect

	class SegTree:

		def __init__(self, init_val, ide_ele, segfunc):
			self.n = len(init_val)
			self.num = 2 ** (self.n - 1).bit_length()
			self.ide_ele = ide_ele
			self.segfunc = segfunc
			self.seg = [ide_ele] * 2 * self.num
			for i in range(self.n):
				self.seg[i + self.num] = init_val[i]
			for i in range(self.num - 1, 0, -1):
				self.seg[i] = self.segfunc(self.seg[2 * i], self.seg[2 * i + 1])

		def update(self, k, x):
			k += self.num
			self.seg[k] = x
			while k:
				k = k >> 1
				self.seg[k] = self.segfunc(self.seg[2 * k], self.seg[2 * k + 1])

		def query(self, l, r):
			if r <= l:
				return self.ide_ele
			l += self.num
			r += self.num
			res = self.ide_ele
			while l < r:
				if r & 1:
					r -= 1
					res = self.segfunc(res, self.seg[r])
				if l & 1:
					res = self.segfunc(res, self.seg[l])
					l += 1
				l = l >> 1
				r = r >> 1
			return res

	def segfunc(x, y):
		if x >= y:
			return x
		else:
			return y
	INF = 10 ** 18
	for _ in range(t):
		(n, k) = map(int, input().split())
		X = list(map(int, input().split()))
		Y = list(map(int, input().split()))
		X.sort()
		A = [0] * n
		R = [0] * n
		for i in range(n):
			j = bisect.bisect_right(X, X[i] + k)
			A[i] = j - i
			R[i] = j
		seg = SegTree(A, 0, segfunc)
		ans = 0
		for l in range(n):
			r = R[l]
			temp = A[l]
			temp += seg.query(r, n)
			ans = max(ans, temp)
		print(ans)
main()


from bisect import *
I = lambda : map(int, input().split())
(t,) = I()
for _ in [0] * t:
	(n, k) = I()
	x = sorted(I())
	I()
	a = q = 0
	m = [n - i - bisect_left(x, x[~i] - k) for i in range(n)]
	for i in range(n):
		a = max(a, q + bisect_right(x, x[i] + k) - i)
		q = max(q, m[~i])
	print(a)


import os
import sys
from math import *
from collections import *
from fractions import *
from bisect import *
from heapq import *
from io import BytesIO, IOBase

def vsInput():
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
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')
ALPHA = 'abcdefghijklmnopqrstuvwxyz'
M = 998244353
EPS = 1e-06

def value():
	return tuple(map(int, input().split()))

def array():
	return [int(i) for i in input().split()]

def Int():
	return int(input())

def Str():
	return input()

def arrayS():
	return [i for i in input().split()]
for _ in range(Int()):
	(n, k) = value()
	x = array()
	y = input()
	C = Counter(x)
	a = [(i, C[i]) for i in C]
	cords = [i for i in sorted(C)]
	pref = [0]
	for i in range(len(cords)):
		pref.append(C[cords[i]] + pref[-1])
	ans_here = [0] * len(cords)
	for i in range(len(cords)):
		j = bisect_right(cords, cords[i] + k) - 1
		ans_here[i] = pref[j + 1] - pref[i]
	optimal = [0] * len(cords)
	ma = 0
	for i in range(len(cords) - 1, -1, -1):
		ma = max(ma, ans_here[i])
		optimal[i] = ma
	ans = 0
	for i in range(len(cords)):
		j = bisect_right(cords, cords[i] + k)
		cur = ans_here[i]
		if j < len(optimal):
			cur += optimal[j]
		ans = max(ans, cur)
	print(ans)


for i in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	input()
	a.sort()
	dp = [0] * n
	dp[0] = 1
	i = 1
	while i < n and a[i] - a[0] <= k:
		dp[i] = i + 1
		i += 1
	l = i
	t = 0
	while i < n:
		while a[i] - a[t] > k:
			t += 1
		dp[i] = max(dp[i - 1], i - t + 1)
		i += 1
	if l == n:
		print(len(a))
	else:
		s = 0
		t = 0
		while l < n:
			while a[l] - a[t] > k:
				t += 1
			s = max(dp[t - 1] + l - t + 1, s)
			l += 1
		print(s)


import bisect
from collections import deque
from sys import stdin
tt = int(stdin.readline())
for loop in range(tt):
	(n, k) = map(int, stdin.readline().split())
	x = list(map(int, stdin.readline().split()))
	y = list(map(int, stdin.readline().split()))
	x.sort()
	unAB = deque([])
	nmax = 0
	ans = 0
	for i in range(n):
		while len(unAB) > 0 and unAB[0][0] < x[i] - k:
			(tx, val) = unAB.popleft()
			nmax = max(nmax, val)
		ind = bisect.bisect_right(x, x[i] + k)
		val = ind - i
		ans = max(ans, nmax + val)
		unAB.append((x[i], val))
	print(ans)


t = int(input())
for p in range(t):
	arr = [int(i) for i in input().split()]
	n = arr[0]
	k = arr[1]
	x_list = [int(i) for i in input().split()]
	y_list = [int(i) for i in input().split()]
	coordinates = []
	for i in range(n):
		coordinates.append([x_list[i], y_list[i]])
	coordinates = sorted(coordinates, key=lambda x: x[0])
	dp = [0 for i in range(n)]
	j = n - 1
	for i in range(n - 1, -1, -1):
		while j >= i and coordinates[j][0] - coordinates[i][0] > k:
			j -= 1
		dp[i] = j - i + 1
	dp1 = list(dp)
	dp1 = dp1[::-1]
	suffix_dp = [0 for i in range(n)]
	suffix_dp[0] = dp1[0]
	for i in range(1, n):
		suffix_dp[i] = max(suffix_dp[i - 1], dp1[i - 1])
	suffix_dp = suffix_dp[::-1]
	dp2 = [0 for i in range(n)]
	dp2[0] = 1
	j = 0
	for i in range(n):
		while j <= i and coordinates[i][0] - coordinates[j][0] > k:
			j += 1
		dp2[i] = i - j + 1
	ans = 0
	for i in range(n):
		if i == n - 1:
			ans = max(ans, dp2[i])
		else:
			ans = max(dp2[i] + suffix_dp[i], ans)
	print(ans)


import math
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	point = {}
	for i in range(n):
		point[x[i]] = point.get(x[i], 0) + 1
	y = list(point.keys())
	y.sort()
	n = len(y)
	ans = [0] * n
	pre = [0] * (n + 1)
	for i in range(1, n + 1):
		pre[i] = pre[i - 1] + point[y[i - 1]]
	ans[-1] = point[y[-1]]
	for i in range(n):
		low = i
		high = n - 1
		while low < high:
			mid = math.ceil((low + high) / 2)
			if y[mid] - y[i] <= k:
				low = mid
			else:
				high = mid - 1
		ans[i] = pre[low + 1] - pre[i]
	for i in range(n - 1):
		ans[-i - 2] = max(ans[-1 - i], ans[-2 - i])
	pr = 0
	ans.append(0)
	for i in range(n):
		low = i
		high = n - 1
		while low < high:
			mid = math.ceil((low + high) / 2)
			if y[mid] - y[i] <= k:
				low = mid
			else:
				high = mid - 1
		pr = max(pr, pre[low + 1] - pre[i] + ans[low + 1])
	print(pr)


for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	a = [int(i) for i in input().split()]
	a.sort()
	input()
	l = []
	r = [0] * n
	j = 0
	for i in range(n):
		while a[i] - a[j] > k:
			j += 1
		l.append(i - j + 1)
	j = n - 1
	for i in range(n - 1, -1, -1):
		while a[j] - a[i] > k:
			j -= 1
		r[i] = j - i + 1
	ml = [l[0]] * n
	for i in range(1, n):
		ml[i] = max(l[i], ml[i - 1])
	mr = [r[-1]] * n
	for i in range(n - 2, -1, -1):
		mr[i] = max(r[i], mr[i + 1])
	ans = 0
	for i in range(n - 1):
		ans = max(ans, ml[i] + mr[i + 1])
	if n == 1:
		print(1)
	else:
		print(ans)


def solve():
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	l = [0] * len(x)
	r = [0] * len(x)
	st = 0
	for i in range(len(x)):
		while x[i] - k > x[st]:
			st += 1
		l[i] = i - st + 1
		if i > 0:
			l[i] = max(l[i], l[i - 1])
	en = len(x) - 1
	for i in reversed(range(len(x))):
		while x[i] + k < x[en]:
			en -= 1
		r[i] = en - i + 1
		if i < len(x) - 1:
			r[i] = max(r[i], r[i + 1])
	ans = 0
	for i in range(len(x)):
		if i == len(x) - 1:
			ans = max(ans, l[i])
		else:
			ans = max(ans, l[i] + r[i + 1])
	print(ans)
T = int(input())
for _ in range(T):
	solve()


from sys import maxsize
INT_MIN = -maxsize
from bisect import bisect_right
from bisect import bisect_left

def Search(arr, low, high, x):
	if low > high:
		return -1
	if x >= arr[high]:
		return high
	mid = int((low + high) / 2)
	if arr[mid] == x:
		return mid
	if mid > 0 and arr[mid - 1] <= x and (x < arr[mid]):
		return mid - 1
	if x < arr[mid]:
		return Search(arr, low, mid - 1, x)
	return Search(arr, mid + 1, high, x)

def construct_segment_tree(a: list, n: int):
	global segtree
	for i in range(n):
		segtree[n + i] = a[i]
	for i in range(n - 1, 0, -1):
		segtree[i] = max(segtree[2 * i], segtree[2 * i + 1])

def update(pos: int, value: int, n: int):
	global segtree
	pos += n
	segtree[pos] = value
	while pos > 1:
		pos //= 2
		segtree[pos] = max(segtree[2 * pos], segtree[2 * pos + 1])

def range_query(left: int, right: int, n: int) -> int:
	global segtree
	left += n
	right += n
	ma = INT_MIN
	while left < right:
		if left & 1:
			ma = max(ma, segtree[left])
			left += 1
		if right & 1:
			right -= 1
			ma = max(ma, segtree[right])
		left //= 2
		right //= 2
	return ma
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	b = list(map(int, input().split()))
	a = list(map(int, input().split()))
	b.sort()
	d = dict()
	for j in range(n):
		d[b[j]] = j
	val = [1] * n
	j = 0
	while j < n:
		res = Search(b, 0, n - 1, b[j] + k)
		if res == -1:
			res = 0
		else:
			val[j] += d[b[res]] - j
		j += 1
	segtree = [0] * (2 * n)
	construct_segment_tree(val, n)
	ans = 0
	j = 0
	while j < n:
		p = bisect_right(b, b[j] + k)
		if p == n:
			ans = max(ans, val[j])
		elif p == n - 1:
			ans = max(ans, val[j] + val[-1])
		else:
			ans = max(ans, val[j] + range_query(p, n, n))
		j += 1
	print(ans)


t = int(input())
f = input
for _ in range(t):
	(n, k) = map(int, f().split())
	x = sorted(map(int, f().split()))
	f()
	r = [0] * n
	c = n - 1
	for i in range(n - 1, -1, -1):
		while x[c] > x[i] + k:
			c -= 1
		r[i] = c
	m = [0] * n
	c = 0
	for i in range(n - 1, -1, -1):
		m[i] = c
		c = max(r[i] - i + 1, c)
	o = [r[i] - i + 1 + m[r[i]] for i in range(n)]
	print(max(o))


import sys
from collections import deque
input = sys.stdin.readline

def inp():
	return int(input())

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

def insr():
	s = input()
	return list(s[:len(s) - 1])

def invr():
	return map(int, input().split())

def digitSum(x):
	c = 0
	while x:
		c += x % 10
		x //= 10
	return c

def solve(k, numbers):
	if not numbers:
		return 0
	numbers.sort()
	v = deque()
	best = [1 for i in range(len(numbers))]
	overallBest = 0
	for (n, i) in enumerate(numbers):
		while v and i - k > v[0]:
			v.popleft()
		if not v:
			v.append(i)
		elif i - v[0] <= k:
			v.append(i)
		if n > 0:
			best[n] = max(best[n - 1], len(v))
		if n >= len(v):
			overallBest = max(overallBest, len(v) + best[n - len(v)])
		else:
			overallBest = best[n]
	return overallBest
lines = inp()
for i in range(lines):
	v = inlt()
	w = inlt()
	_ = inlt()
	print(solve(v[1], w))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	y = input()
	a.sort()
	l = [0] * (n + 1)
	r = [0] * (n + 1)
	i = 0
	for j in range(n):
		while a[j] - a[i] > k:
			i += 1
		l[j + 1] = j - i + 1
		l[j + 1] = max(l[j], l[j + 1])
	i = n - 1
	for j in range(n - 1, -1, -1):
		while a[i] - a[j] > k:
			i -= 1
		r[j] = i - j + 1
		r[j] = max(r[j], r[j + 1])
	maximum = 0
	for i in range(n + 1):
		maximum = max(maximum, l[i] + r[i])
	print(maximum)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	(x, y) = ([int(i) for i in input().split()], [int(i) for i in input().split()])
	x.sort()
	x.append(9999999999999999999)
	(t, ans, arr, r) = (0, 0, [0] * (n + 5), 0)
	ll = 0
	for i in range(n):
		while x[r + 1] - x[i] <= k:
			r = r + 1
		can = r - i + 1
		arr[i] = (can, x[i] + k + 1)
		while ll <= i and arr[ll][1] < x[i]:
			t = max([t, arr[ll][0]])
			ll = ll + 1
		ans = max([ans, can + t])
	r = 0
	for i in range(n):
		while x[r + 1] - x[i] <= k * 2 + 1:
			r = r + 1
		ans = max([ans, r - i + 1])
	print(ans)


def iin():
	return int(input())

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

def main():
	from bisect import bisect_right as br, bisect_left as bl
	t = iin()
	while t:
		t -= 1
		(n, k) = lin()
		x = lin()
		y = lin()
		x.sort()
		sol = []
		for i in range(n):
			val = x[i] + k
			pos = br(x, val)
			sol.append([x[i], pos - i])
		s1 = [i for (i, j) in sol]
		a1 = [j for (i, j) in sol]
		for i in range(n - 2, -1, -1):
			a1[i] = max(a1[i], a1[i + 1])
		ans = max(sol, key=lambda x: x[1])[1]
		for i in range(n):
			(val, count) = sol[i]
			pos = bl(s1, val + k + 1)
			if pos < n:
				ans = max(count + a1[pos], ans)
		print(ans)
main()


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	lft_m = [0] * (n + 1)
	right_m = [0] * (n + 1)
	l = 0
	for j in range(n):
		while x[j] - x[l] > k:
			l += 1
		right_m[j] = j - l + 1
		if j > 0:
			right_m[j] = max(right_m[j], right_m[j - 1])
	l = n - 1
	for j in range(n - 1, -1, -1):
		while x[l] - x[j] > k:
			l -= 1
		lft_m[j] = l - j + 1
		if j < n - 1:
			lft_m[j] = max(lft_m[j], lft_m[j + 1])
	ans = 0
	for j in range(n):
		ans = max(ans, right_m[j] + lft_m[j + 1])
	print(ans)


from sys import stdin

def inp():
	return stdin.buffer.readline().rstrip().decode('utf8')

def itg():
	return int(stdin.buffer.readline())

def mpint():
	return map(int, stdin.buffer.readline().split())
for __ in range(itg()):
	(n, k) = mpint()
	arr = list(mpint())
	arr.sort()
	inp()
	left = [0] * n
	j = 0
	for i in range(n):
		while arr[i] - arr[j] > k:
			j += 1
		left[i] = i - j + 1
	right = [0] * n
	j = n - 1
	for i in range(n - 1, -1, -1):
		while arr[j] - arr[i] > k:
			j -= 1
		right[i] = j - i + 1
	for i in range(1, n):
		left[i] = max(left[i], left[i - 1])
	for i in range(n - 2, -1, -1):
		right[i] = max(right[i], right[i + 1])
	ans = left[-1]
	for i in range(n - 1):
		ans = max(ans, left[i] + right[i + 1])
	print(ans)


from sys import stdin
for _ in range(int(stdin.readline())):
	(n, k) = map(int, stdin.readline().split())
	arr_x = list(map(int, stdin.readline().split()))
	arr_y = list(map(int, stdin.readline().split()))
	arr_x.sort()
	left = [0] * (n + 1)
	i = 0
	j = 0
	while i < n:
		while j <= i and arr_x[i] - arr_x[j] > k:
			j += 1
		left[i + 1] = max(left[i], i - j + 1)
		i += 1
	right = [0] * (n + 1)
	i = n - 1
	j = n - 1
	while i >= 0:
		while j >= i and arr_x[j] - arr_x[i] > k:
			j -= 1
		right[i] = max(right[i + 1], j - i + 1)
		i -= 1
	ans = 0
	for i in range(n + 1):
		ans = max(ans, left[i] + right[i])
	print(ans)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf
from collections import defaultdict as dd, deque, Counter as C
from itertools import combinations as comb, permutations as perm
from bisect import bisect_left as bl, bisect_right as br, bisect
from time import perf_counter
from fractions import Fraction
from decimal import Decimal
mod = pow(10, 9) + 7
mod2 = 998244353

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

def out(var, end='\n'):
	sys.stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	sys.stdout.write(' '.join(map(str, var)) + end)

def l():
	return list(sp())

def sp():
	return map(int, data().split())

def ssp():
	return map(str, data().split())

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(n, val) for j in range(m)]
for _ in range(int(data())):
	(n, k) = sp()
	x = C(l())
	y = l()
	x = sorted(x.items(), key=lambda abc: abc[0])
	n = len(x)
	for i in range(n):
		x[i] = list(x[i])
		x[i].append(i)
	window = deque()
	cnt = 0
	answer = [0] * n
	for i in range(n):
		window.append(x[i])
		cnt += x[i][1]
		while window and window[-1][0] - window[0][0] > k:
			cnt -= window.popleft()[1]
		answer[i] = max(answer[i - 1], cnt) if i != 0 else cnt
	window = deque()
	result = max(answer)
	cnt = 0
	for i in range(1, n):
		window.append(x[i])
		cnt += x[i][1]
		while window and window[-1][0] - window[0][0] > k:
			cnt -= window.popleft()[1]
		if window:
			result = max(result, answer[window[0][2] - 1] + cnt)
	out(result)


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 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 print_list(l):
	print(' '.join(map(str, l)))
import bisect as bs
from collections import Counter
from collections import defaultdict as dc
for _ in range(N()):
	(n, k) = RL()
	a = RLL()
	input()
	dic = Counter(a)
	x = list(dic.keys())
	x.sort()
	s = [0, dic[x[0]]]
	nn = len(x)
	for i in range(1, nn):
		s.append(s[-1] + dic[x[i]])
	pair = [0] * nn
	balls = [0] * nn
	for i in range(nn):
		pair[i] = bs.bisect_right(x, x[i] + k)
		balls[i] = s[pair[i]] - s[i]
	mr = [0] * (nn + 1)
	for i in range(nn - 1, -1, -1):
		mr[i] = max(balls[i], mr[i + 1])
	ans = 0
	for i in range(nn):
		ans = max(ans, balls[i] + mr[pair[i]])
	print(ans)


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

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		x = list(map(int, input().split()))
		y = list(map(int, input().split()))
		x.sort()
		ans = 0
		curr = 0
		ls = [0] * (n + 5)
		for i in range(n - 1, -1, -1):
			left = i
			right = bisect_right(x, x[i] + k)
			curr = max(curr, right - left)
			ls[i] = curr
		for i in range(n):
			left = i
			right = bisect_right(x, x[i] + k)
			ans = max(ans, right - left + ls[right])
		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()


import math
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
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 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
for ik in range(int(input())):
	(a, b) = map(int, input().split())
	n = a
	k = b
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	ans = []
	f = 0
	ans1 = 0
	for i in range(n):
		d = binarySearchCount(x, len(x), x[i] + b)
		ans.append(d - i)
	s = SegmentTree(ans)
	for i in range(n):
		d = binarySearchCount(x, len(x), x[i] + b)
		if d == n:
			ans1 = max(ans1, d - i)
			break
		else:
			d += s.query(d, n - 1) - i
			ans1 = max(ans1, d)
	print(ans1)


import sys, math
import io, os
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

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

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')
from decimal import Decimal
mod = int(1000000000.0) + 7
INF = 2 ** 32

def cal(n):
	ans = 0
	while n:
		ans += n % 10
		n //= 10
	return ans
for t in range(int(data())):
	(n, k) = mdata()
	ans = 1
	X = sorted(mdata())
	Y = mdata()
	q = deque()
	d = dd(int)
	m = 0
	for i in range(n):
		while q and X[i] - k > q[0]:
			m = max(m, d[q.popleft()])
		q.append(X[i])
		d[X[i]] = len(q)
		ans = max(ans, m + len(q))
	out(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	l1 = list(map(int, input().split()))
	l2 = list(map(int, input().split()))
	l1.sort()
	if n == 1:
		print(1)
		continue
	left = [0] * n
	right = [0] * n
	(i, j) = (0, 0)
	while j < n:
		if l1[j] - l1[i] <= k:
			if j:
				left[j] = max(left[j - 1], j - i + 1)
			else:
				left[j] = j - i + 1
			j += 1
		else:
			i += 1
	(i, j) = (n - 1, n - 1)
	while j >= 0:
		if l1[i] - l1[j] <= k:
			if j != n - 1:
				right[j] = max(right[j - 1], i - j + 1)
			else:
				right[j] = i - j + 1
			j -= 1
		else:
			i -= 1
	ans = 0
	for i in range(0, n - 1):
		ans = max(ans, left[i] + right[i + 1])
	print(ans)


from functools import cmp_to_key
from collections import deque
from heapq import heappush, heappop
from math import log, ceil
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')
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))

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

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

def ii():
	return int(inp())

def li(lag=0):
	l = list(map(int, inp().split()))
	if lag != 0:
		for i in range(len(l)):
			l[i] += lag
	return l

def mi(lag=0):
	matrix = list()
	for i in range(n):
		matrix.append(li(lag))
	return matrix

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

def print_list(lista, space=' '):
	print(space.join(map(str, lista)))

class UnionFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		if self.size[a] < self.size[b]:
			(a, b) = (b, a)
		self.num_sets -= 1
		self.parent[b] = a
		self.size[a] += self.size[b]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

def bisect_left(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] < x:
			left = mid + 1
		else:
			right = mid
	return left

def bisect_right(a, x):
	left = 0
	right = len(a)
	while left < right:
		mid = (left + right) // 2
		if a[mid] > x:
			right = mid
		else:
			left = mid + 1
	return left

def bisect_elements(a, x):
	return bisect_right(a, x) - bisect_left(a, x)

def custom_sort(lista):

	def cmp(x, y):
		if x + y > y + x:
			return 1
		else:
			return -1
	return sorted(lista, key=cmp_to_key(cmp))
MOD = 10 ** 9 + 7
maxN = 10 ** 5
FACT = [0] * maxN

def add(x, y):
	return (x + y) % MOD

def multiply(x, y):
	return x * y % MOD

def power(x, y):
	if y == 0:
		return 1
	elif y % 2:
		return multiply(x, power(x, y - 1))
	else:
		a = power(x, y // 2)
		return multiply(a, a)

def inverse(x):
	return power(x, MOD - 2)

def divide(x, y):
	return multiply(x, inverse(y))

def allFactorials():
	FACT[0] = 1
	for i in range(1, maxN):
		FACT[i] = multiply(i, FACT[i - 1])

def coeffBinom(n, k):
	if n < k:
		return 0
	return divide(FACT[n], multiply(FACT[k], FACT[n - k]))

def primes(N):
	smallest_prime = [1] * (N + 1)
	prime = []
	smallest_prime[0] = 0
	smallest_prime[1] = 0
	for i in range(2, N + 1):
		if smallest_prime[i] == 1:
			prime.append(i)
			smallest_prime[i] = i
		j = 0
		while j < len(prime) and i * prime[j] <= N:
			smallest_prime[i * prime[j]] = min(prime[j], smallest_prime[i])
			j += 1
	return (prime, smallest_prime)

def gcd(a, b):
	a = abs(a)
	b = abs(b)
	(s, t, r) = (0, 1, b)
	(old_s, old_t, old_r) = (1, 0, a)
	while r != 0:
		quotient = old_r // r
		(old_r, r) = (r, old_r - quotient * r)
		(old_s, s) = (s, old_s - quotient * s)
		(old_t, t) = (t, old_t - quotient * t)
	return (old_r, old_s, old_t)

def create_graph(n, m, undirected=1, unweighted=1):
	graph = [[] for i in range(n)]
	if unweighted:
		for i in range(m):
			[x, y] = li(lag=-1)
			graph[x].append(y)
			if undirected:
				graph[y].append(x)
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			graph[x].append([y, w])
			if undirected:
				graph[y].append([x, w])
	return graph

def create_tree(n, unweighted=1):
	children = [[] for i in range(n)]
	if unweighted:
		for i in range(n - 1):
			[x, y] = li(lag=-1)
			children[x].append(y)
			children[y].append(x)
	else:
		for i in range(n - 1):
			[x, y, w] = li(lag=-1)
			w += 1
			children[x].append([y, w])
			children[y].append([x, w])
	return children

def create_edges(m, unweighted=0):
	edges = list()
	if unweighted:
		for i in range(m):
			edges.append(li(lag=-1))
	else:
		for i in range(m):
			[x, y, w] = li(lag=-1)
			w += 1
			edges.append([w, x, y])
	return edges

def dist(tree, n, A, B=-1):
	s = [[A, 0]]
	(massimo, massimo_nodo) = (0, 0)
	distanza = -1
	v = [-1] * n
	while s:
		(el, dis) = s.pop()
		if dis > massimo:
			massimo = dis
			massimo_nodo = el
		if el == B:
			distanza = dis
		for child in tree[el]:
			if v[child] == -1:
				v[child] = 1
				s.append([child, dis + 1])
	return (massimo, massimo_nodo, distanza)

def diameter(tree):
	(_, foglia, _) = dist(tree, n, 0)
	(diam, _, _) = dist(tree, n, foglia)
	return diam

def dfs(graph, n, A):
	v = [-1] * n
	s = [[A, 0]]
	v[A] = 0
	while s:
		(el, dis) = s.pop()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def bfs(graph, n, A):
	v = [-1] * n
	s = deque()
	s.append([A, 0])
	v[A] = 0
	while s:
		(el, dis) = s.popleft()
		for child in graph[el]:
			if v[child] == -1:
				v[child] = dis + 1
				s.append([child, dis + 1])
	return v

def connected(graph, n):
	v = dfs(graph, n, 0)
	for el in v:
		if el == -1:
			return False
	return True

def topological(graph, n):
	indegree = [0] * n
	for el in range(n):
		for child in graph[el]:
			indegree[child] += 1
	s = deque()
	for el in range(n):
		if indegree[el] == 0:
			s.append(el)
	order = []
	while s:
		el = s.popleft()
		order.append(el)
		for child in graph[el]:
			indegree[child] -= 1
			if indegree[child] == 0:
				s.append(child)
	if n == len(order):
		return (False, order)
	else:
		return (True, [])

def bipartite(graph, n):
	color = [-1] * n
	color[0] = 0
	s = [0]
	while s:
		el = s.pop()
		for child in graph[el]:
			if color[child] == color[el]:
				return False
			if color[child] == -1:
				s.append(child)
			color[child] = 1 - color[el]
	return True

def dijkstra(graph, n, A):
	dist = [float('inf') for i in range(n)]
	prev = [-1 for i in range(n)]
	dist[A] = 0
	pq = []
	heappush(pq, [0, A])
	while pq:
		[d_v, v] = heappop(pq)
		if d_v != dist[v]:
			continue
		for (to, w) in graph[v]:
			if dist[v] + w < dist[to]:
				dist[to] = dist[v] + w
				prev[to] = v
				heappush(pq, [dist[to], to])
	return (dist, prev)

def dijkstra_0_1(graph, n, A):
	dist = [float('inf') for i in range(n)]
	dist[A] = 0
	p = deque()
	p.append(A)
	while p:
		v = p.popleft()
		for (to, w) in graph[v]:
			if dist[v] + w < dist[to]:
				dist[to] = dist[v] + w
			if w == 1:
				q.append(to)
			else:
				q.appendleft(to)
	return dist

def floyd_warshall(graph, n):
	dist = [[float('inf') for _ in range(n)] for _ in range(n)]
	for i in range(n):
		dist[i][i] = 0
		for (child, d) in graph[i]:
			dist[i][child] = d
			dist[child][i] = d
	for k in range(n):
		for i in range(n):
			for j in range(j):
				dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
	return dist

def minimum_spanning_tree(edges, n):
	edges = sorted(edges)
	union_find = UnionFind(n)
	used_edges = list()
	for (w, x, y) in edges:
		if union_find.find(x) != union_find.find(y):
			union_find.merge(x, y)
			used_edges.append([w, x, y])
	return used_edges

def parents_children_root_unrooted_tree(tree, n, root=0):
	q = deque()
	visited = [0] * n
	parent = [-1] * n
	children = [[] for i in range(n)]
	q.append(root)
	while q:
		all_done = 1
		visited[q[0]] = 1
		for child in tree[q[0]]:
			if not visited[child]:
				all_done = 0
				q.appendleft(child)
		if all_done:
			for child in tree[q[0]]:
				if parent[child] == -1:
					parent[q[0]] = child
					children[child].append(q[0])
			q.popleft()
	return (parent, children)

def all_longest_path_passing_from_node(parent, children, n):
	q = deque()
	visited = [len(children[i]) for i in range(n)]
	downwards = [[0, 0] for i in range(n)]
	upward = [1] * n
	longest_path = [1] * n
	for i in range(n):
		if not visited[i]:
			q.append(i)
			downwards[i] = [1, 0]
	while q:
		node = q.popleft()
		if parent[node] != -1:
			visited[parent[node]] -= 1
			if not visited[parent[node]]:
				q.append(parent[node])
		else:
			root = node
		for child in children[node]:
			downwards[node] = sorted([downwards[node][0], downwards[node][1], downwards[child][0] + 1], reverse=True)[0:2]
	s = [node]
	while s:
		node = s.pop()
		if parent[node] != -1:
			if downwards[parent[node]][0] == downwards[node][0] + 1:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][1])
			else:
				upward[node] = 1 + max(upward[parent[node]], downwards[parent[node]][0])
		longest_path[node] = downwards[node][0] + downwards[node][1] + upward[node] - min([downwards[node][0], downwards[node][1], upward[node]]) - 1
		for child in children[node]:
			s.append(child)
	return longest_path

def finding_ancestors(parent, queries, n):
	steps = int(ceil(log(n, 2)))
	ancestors = [[-1 for i in range(n)] for j in range(steps)]
	ancestors[0] = parent
	for i in range(1, steps):
		for node in range(n):
			if ancestors[i - 1][node] != -1:
				ancestors[i][node] = ancestors[i - 1][ancestors[i - 1][node]]
	result = []
	for (node, k) in queries:
		ans = node
		if k >= n:
			ans = -1
		i = 0
		while k > 0 and ans != -1:
			if k % 2:
				ans = ancestors[i][ans]
			k = k // 2
			i += 1
		result.append(ans)
	return result

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def nearest_from_the_left_smaller_elements(arr):
	n = len(arr)
	res = [-1] * n
	s = []
	for (i, el) in enumerate(arr):
		while s and s[-1] >= el:
			s.pop()
		if s:
			res[i] = s[-1]
		s.append(el)
	return res

def sliding_window_minimum(arr, k):
	res = []
	q = deque()
	for (i, el) in enumerate(arr):
		while q and arr[q[-1]] >= el:
			q.pop()
		q.append(i)
		while q and q[0] <= i - k:
			q.popleft()
		if i >= k - 1:
			res.append(arr[q[0]])
	return res

def somma(s):
	su = 0
	while s > 0:
		su += s % 10
		s = s // 10
	return su
for test in range(ii()):
	[n, k] = li()
	x = li()
	y = li()
	x = sorted(x)
	start = [0 for i in range(n)]
	end = [0 for i in range(n)]
	for i in range(n):
		el = x[i]
		fine = bisect_right(x, el + k)
		inizio = bisect_left(x, el - k)
		start[i] = fine - i
		end[i] = i - inizio + 1
	pref = [0] * (n + 1)
	suf = [0] * (n + 1)
	for i in range(1, n + 1):
		pref[i] = max(pref[i - 1], end[i - 1])
	for i in range(n - 1, -1, -1):
		suf[i] = max(suf[i + 1], start[i])
	res = 0
	for i in range(n):
		res = max(res, pref[i] + suf[i])
	print(res)


t = int(input())
for i in range(t):
	params = input()
	(n, k) = (int(params.split()[0]), int(params.split()[1]))
	coordinates = input()
	something = input()
	numbers = list(map(int, coordinates.split()))
	numbers.sort()
	if numbers[-1] - numbers[0] <= 2 * k or len(numbers) == 1:
		print(n)
		continue
	right = [0] * len(numbers)
	left = [0] * len(numbers)
	left[0] = 1
	p = 0
	q = 0
	while True:
		while q < len(numbers) and numbers[q] - numbers[p] <= k:
			left[q] = q - p + 1
			q += 1
		if q == len(numbers):
			right[p] = q - p
			break
		right[p] = q - p
		while numbers[q] - numbers[p] > k:
			p += 1
			right[p] = q - p
		if numbers[q] - numbers[p] == k:
			right[p] = right[p - 1]
	for j in range(0, len(numbers) - 1):
		left[j + 1] = max(left[j], left[j + 1])
	for j in range(len(numbers) - 1, 0, -1):
		right[j - 1] = max(right[j - 1], right[j])
	maximum = 0
	for j in range(0, len(numbers) - 1):
		maximum = max(left[j] + right[j + 1], maximum)
	print(maximum)


from collections import defaultdict
from collections import defaultdict
import bisect

class SegmentTree(object):

	def __init__(self, A, dot, unit):
		n = 1 << (len(A) - 1).bit_length()
		tree = [unit] * (2 * n)
		for (i, v) in enumerate(A):
			tree[i + n] = v
		for i in range(n - 1, 0, -1):
			tree[i] = dot(tree[i << 1], tree[i << 1 | 1])
		self._n = n
		self._tree = tree
		self._dot = dot
		self._unit = unit

	def __getitem__(self, i):
		return self._tree[i + self._n]

	def update(self, i, v):
		i += self._n
		self._tree[i] = v
		while i != 1:
			i >>= 1
			self._tree[i] = self._dot(self._tree[i << 1], self._tree[i << 1 | 1])

	def add(self, i, v):
		self.update(i, self[i] + v)

	def sum(self, l, r):
		l += self._n
		r += self._n
		l_val = r_val = self._unit
		while l < r:
			if l & 1:
				l_val = self._dot(l_val, self._tree[l])
				l += 1
			if r & 1:
				r -= 1
				r_val = self._dot(self._tree[r], r_val)
			l >>= 1
			r >>= 1
		return self._dot(l_val, r_val)

def main():
	t = int(input())
	for _ in range(t):
		(n, k) = map(int, input().split())
		INF = pow(10, 18)
		xtemp = list(map(int, input().split()))
		ytemp = list(map(int, input().split()))
		dic = defaultdict(int)
		for x in xtemp:
			dic[x] += 1
		Z = list(dic.items())
		Z.sort()
		X = []
		P = []
		SP = [0]
		for (x, p) in Z:
			X.append(x)
			P.append(p)
			SP.append(SP[-1] + p)
		P.append(INF)
		A = []
		for i in range(len(X)):
			boundary = X[i] + k
			idx = bisect.bisect_right(X, boundary)
			ret = SP[idx] - SP[i]
			A.append(ret)
		Tree = SegmentTree(A, max, 0)
		ans = -INF
		for i in range(len(X)):
			first = A[i]
			nxt_idx = bisect.bisect_right(X, X[i] + k)
			second = Tree.sum(nxt_idx, len(A))
			ans = max(ans, first + second)
		print(ans)
main()


(T,) = map(int, input().split())
for _ in range(T):
	(N, k) = map(int, input().split())
	X = list(sorted(list(map(int, input().split())))) + [10 ** 18]
	Y = list(map(int, input().split())) + [10 ** 18]
	yi = 0
	Z = [0] * N
	V = [1] * N
	for i in range(N):
		while X[yi + 1] <= X[i] + k:
			yi += 1
			V[yi] = yi - i + 1
		Z[i] = yi - i + 1
	for i in range(1, N):
		V[i] = max(V[i], V[i - 1])
	for i in range(N - 2, -1, -1):
		Z[i] = max(Z[i], Z[i + 1])
	R = 1
	for i in range(N - 1):
		R = max(R, V[i] + Z[i + 1])
	print(R)


for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	(nums, _) = (sorted(map(int, input().split())), list(map(int, input().split())))
	if 2 * k >= nums[-1] - nums[0]:
		print(len(nums))
		continue
	f = [0] * (n + 1)
	l = ans = 0
	for (r, v) in enumerate(nums):
		while v - nums[l] > k:
			l += 1
		f[r + 1] = max(f[r], r - l + 1)
		ans = max(ans, f[l] + r - l + 1)
	print(ans)


for i in range(int(input())):
	(n, k) = list(map(int, input().split()))
	x = sorted(map(int, input().split()))
	input()
	a = []
	j = 0
	for i in range(n):
		while j < n and x[j] - x[i] <= k:
			j += 1
		a.append(j - i)
	c = a[:]
	a1 = a[:]
	for i in range(1, n):
		a[i] = max(a[i], a[i - 1])
	for i in range(n - 2, -1, -1):
		a1[i] = max(a1[i], a1[i + 1])
	j = n - 1
	l = n - 1
	z = 0
	for i in range(n - 1, -1, -1):
		while x[l] - x[i] > k:
			l -= 1
		b = 0
		if l != n - 1:
			b = a1[l + 1]
		while j >= 0 and x[i - 1] - x[j] <= k:
			j -= 1
		if j >= 0:
			b = max(b, a[j])
		else:
			z = max(z, l + 1)
		z = max(z, b + c[i])
	print(min(z, n))


import sys
input = sys.stdin.buffer.readline

def print(val):
	sys.stdout.write(str(val) + '\n')

def prog():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		x = list(map(int, input().split()))
		y = list(map(int, input().split()))
		x.sort()
		most_at_point = [0] * n
		most_after_point = [0] * (n + 1)
		tot = 0
		j = -1
		for i in range(n):
			while j + 1 < n and x[j + 1] <= x[i] + k:
				j += 1
				tot += 1
			most_at_point[i] = tot
			tot -= 1
		for i in range(n - 1, -1, -1):
			most_after_point[i] = max(most_after_point[i + 1], most_at_point[i])
		best = 0
		j = 0
		for i in range(n):
			while j < n and x[j] <= x[i] + k:
				j += 1
			if j == n:
				best = max(best, most_at_point[i])
			else:
				best = max(best, most_at_point[i] + most_after_point[j])
		print(best)
prog()


t = int(input())
for i in range(t):
	(n, k) = list(map(int, input().split()))
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	num = x[0]
	for j in range(n):
		x[j] -= num
	j = 0
	while j < n:
		if x[j] <= k:
			j += 1
		else:
			break
	if j == n or x[-1] - x[0] <= 2 * k or n == 1:
		print(n)
	else:
		r = [j]
		p = j - 1
		for j in range(1, n):
			while p < n:
				temp = x[p] - x[j]
				if temp <= k:
					p += 1
				else:
					break
			r.append(min(p, n) - j)
			p -= 1
		l = []
		q = 0
		for j in range(n):
			while x[j] - x[q] > k:
				q += 1
			l.append(j - q + 1)
		pref = [l[0]]
		suff = [0] * n
		suff[-1] = r[-1]
		for j in range(1, n):
			pref.append(max(pref[-1], l[j]))
			suff[-j - 1] = max(suff[-j], r[-j - 1])
		ans = 0
		for j in range(n - 1):
			ans = max(ans, pref[j] + suff[j + 1])
		print(ans)


import sys, math
from collections import deque

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

def max_prefix(arr, size):
	q = deque([arr[0]])
	p_arr = [1]
	max_arr = [1]
	for i in range(1, len(arr)):
		while len(q) > 0 and q[0] < arr[i] - size:
			deque.popleft(q)
		deque.append(q, arr[i])
		p_arr.append(len(q))
		max_arr.append(max(max_arr[-1], p_arr[-1]))
	return max_arr

def max_suffix(arr, size):
	q = deque([arr[-1]])
	s_arr = [1]
	max_arr = [1]
	for i in range(-2, -len(arr) - 1, -1):
		while len(q) > 0 and q[0] > arr[i] + size:
			deque.popleft(q)
		deque.append(q, arr[i])
		s_arr.append(len(q))
		max_arr.append(max(max_arr[-1], s_arr[-1]))
	max_arr.reverse()
	return max_arr
t = int(input())
for _ in range(t):
	(n, k) = get_int()
	pt_x = get_int()
	pt_y = get_int()
	pt_x.sort()
	p_arr = max_prefix(pt_x, k)
	s_arr = max_suffix(pt_x, k)
	max_arr = [p_arr[0] + (s_arr[1] if len(s_arr) > 1 else 0)]
	for i in range(1, n - 1):
		max_arr.append(max(max_arr[-1], p_arr[i] + s_arr[i + 1]))
	if n > 1:
		max_arr.append(max(max_arr[-1], p_arr[-1]))
	print(max(max_arr))


t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	xs = map(int, input().split())
	ys = map(int, input().split())
	points_at_x = dict()
	for x in xs:
		points_at_x[x] = points_at_x.get(x, 0) + 1
	points = sorted(points_at_x.keys())
	m = len(points)
	saved = [0] * m
	p_ends = [m] * m
	start = 0
	end = 0
	while start < m and start <= end and (end < m + 1):
		if end < m and points[end] - points[start] <= k:
			saved[start] += points_at_x[points[end]]
			end += 1
		else:
			p_ends[start] = end
			start += 1
			if start < m:
				saved[start] = saved[start - 1] - points_at_x[points[start - 1]]
	max_saved = [0] * m
	max_saved[m - 1] = saved[m - 1]
	for j in range(m - 1):
		max_saved[m - 2 - j] = max(max_saved[m - 1 - j], saved[m - 2 - j])
	result = 0
	for j in range(m):
		temp = saved[j]
		temp2 = p_ends[j]
		if temp2 < m:
			temp += max_saved[temp2]
		result = max(result, temp)
	print(result)


def arr(A, k):
	n = len(A)
	pre = [0] * n
	l = 0
	r = 0
	while r < n:
		if abs(A[r] - A[l]) <= k:
			r += 1
		else:
			while l < r and abs(A[r] - A[l]) > k:
				l += 1
			r += 1
		pre[r - 1] = r - l
	return pre

def answer(n, k, A):
	if n == 1:
		return 1
	A.sort()
	pre = arr(A, k)
	suff = arr(A[::-1], k)
	suff = suff[::-1]
	maxip = [0] * n
	maxi = 0
	maxis = [0] * n
	for i in range(n):
		maxi = max(maxi, pre[i])
		maxip[i] = maxi
	maxi = 0
	for i in range(n - 1, -1, -1):
		maxi = max(maxi, suff[i])
		maxis[i] = maxi
	maxi = 0
	for i in range(n - 1):
		maxi = max(maxi, maxip[i] + maxis[i + 1])
	return maxi
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	arr1 = list(map(int, input().split()))
	arr2 = list(map(int, input().split()))
	print(answer(n, k, arr1))


import sys
import bisect as bi
import math as mt
import collections as cc
import sys
I = lambda : list(map(int, input().split()))
for tc in range(int(input())):
	(n, k) = I()
	x = sorted(I())
	y = sorted(I())
	ans = 0
	ma = [0] * (n + 3)
	for i in range(n - 1, -1, -1):
		(l, r) = (x[i], x[i] + k)
		ll = bi.bisect_left(x, l)
		rr = bi.bisect_right(x, r)
		now = rr - ll
		ma[i] = max(now, ma[i + 1])
		ans = max(ans, now + ma[rr])
	print(ans)


from bisect import bisect_left
import os
import sys
from io import BytesIO, IOBase
from collections import Counter, defaultdict
from collections import deque
from functools import cmp_to_key
import math
import heapq

def sin():
	return input()

def ain():
	return list(map(int, sin().split()))

def sain():
	return input().split()

def iin():
	return int(sin())
MAX = float('inf')
MIN = float('-inf')
MOD = 1000000007

def sieve(n):
	prime = [True for i in range(n + 1)]
	p = 2
	while p * p <= n:
		if prime[p] == True:
			for i in range(p * p, n + 1, p):
				prime[i] = False
		p += 1
	s = set()
	for p in range(2, n + 1):
		if prime[p]:
			s.add(p)
	return s

def readTree(n, m):
	adj = [deque([]) for _ in range(n + 1)]
	for _ in range(m):
		(u, v) = ain()
		adj[u].append(v)
		adj[v].append(u)
	return adj

def main():
	for _ in range(iin()):
		(n, k) = ain()
		x = ain()
		y = ain()
		x.sort()
		i = 0
		j = 0
		d = deque([])
		c = 0
		while i < n and j < n:
			if x[j] == x[i]:
				c += 1
				j += 1
				continue
			if x[j] - x[i] <= k:
				c += 1
				j += 1
			else:
				d.append(c)
				c -= 1
				i += 1
		rem = n - i
		xx = rem
		for i in range(rem):
			d.append(xx)
			xx -= 1
		maxd = deque([])
		maxi = MIN
		for i in range(n - 1, -1, -1):
			maxi = max(maxi, d[i])
			maxd.appendleft(maxi)
		ans = MIN
		for i in range(n):
			ans = max(ans, d[i] + maxd[min(n - 1, i + d[i])])
		if ans > n:
			print(n)
		else:
			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')
if os.getcwd() == 'D:\\code':
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	input = lambda : sys.stdin.readline().rstrip('\r\n')
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')
from collections import Counter
import heapq
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	x = sorted(x)
	y = list(map(int, input().split()))
	end = [0] * (n + 1)
	j = 0
	for i in range(n):
		while x[i] - x[j] > k:
			j += 1
		if i > 0:
			end[i] = max(end[i - 1], i - j + 1)
		else:
			end[i] = j - i + 1
	start = [0] * (n + 2)
	j = n - 1
	for i in range(n - 1, -1, -1):
		while x[j] - x[i] > k:
			j -= 1
		start[i] = max(start[i + 1], j - i + 1)
	ans = 0
	for i in range(n):
		ans = max(ans, end[i] + start[i + 1])
	print(ans)


import sys
stdin = sys.stdin
stdout = sys.stdout

def binSearch(arr, num, start, end):
	while start != end:
		mid = (start + end) // 2
		if arr[mid] >= num:
			end = mid
		else:
			start = mid + 1
	return start
test = int(stdin.readline())
for t in range(test):
	(n, k) = [int(_) for _ in stdin.readline().split()]
	x = [int(_) for _ in stdin.readline().split()]
	y = [int(_) for _ in stdin.readline().split()]
	x.sort()
	dp = [0 for i in range(n + 1)]
	dp2 = [0 for i in range(n + 1)]
	for i in range(1, len(x) + 1):
		dp[i] = dp[i - 1]
		dp2[i] = dp2[i - 1]
		covered = x[i - 1] - k
		idx = binSearch(x, covered, 0, i - 1)
		dp[i] = max(dp[i], i - idx)
		dp2[i] = max(dp2[i], i - idx + dp[idx])
	stdout.write(f'{dp2[n]}\n')


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

def solve(N, K, X, Y):
	X = sorted(X)

	def maxSave(A, rev=False):
		window = deque()
		dp = []
		mx = 0
		dp.append(mx)
		for x in A:
			window.append(x)
			while abs(window[-1] - window[0]) > K:
				window.popleft()
			mx = max(mx, len(window))
			dp.append(mx)
		return dp
	forward = maxSave(X)
	backward = maxSave(X[::-1], True)
	best = 0
	for i in range(N + 1):
		best = max(best, forward[i] + backward[N - i])
	return best
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = int(input())
for tc in range(1, TC + 1):
	(N, K) = [int(x) for x in input().split()]
	X = [int(x) for x in input().split()]
	Y = [int(x) for x in input().split()]
	ans = solve(N, K, X, Y)
	print(ans)


TC = int(input())
for tc in range(TC):
	(N, K) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	if N < 3:
		print(N)
		continue
	X.sort()
	l = [0 for _ in X]
	r = [0 for _ in X]
	j = 0
	for (i, x) in enumerate(X):
		while x > X[j] + K:
			j += 1
		l[i] = i - j + 1
	j = N - 1
	for i in range(N - 1, -1, -1):
		while X[j] > X[i] + K:
			j -= 1
		r[i] = j - i + 1
	max_l = l.copy()
	max_r = r.copy()
	for (i, ml) in enumerate(l[1:], 1):
		max_l[i] = max(ml, max_l[i - 1])
	for i in range(N - 2, -1, -1):
		max_r[i] = max(r[i], max_r[i + 1])
	result = 0
	for i in range(N - 1):
		result = max(result, max_l[i] + max_r[i + 1])
	print(result)


import math
from collections import deque
from collections import defaultdict
t = int(input())
while t > 0:
	t -= 1
	(n, k) = map(int, input().strip().split(' '))
	x = list(map(int, input().strip().split(' ')))
	y = list(map(int, input().strip().split(' ')))
	x.sort()
	ans = 0
	d = deque()
	dd = defaultdict(int)
	f1 = 0
	for i in range(n):
		while d and x[i] - k > d[0]:
			f1 = max(f1, dd[d.popleft()])
		d.append(x[i])
		ans = max(ans, f1 + len(d))
		dd[x[i]] = len(d)
	print(ans)


from sys import stdin, stdout

class SOLVE:

	def bsearch(self, left, right, j, x, k, pos, cmd):
		if left > right:
			return pos
		mid = (left + right) // 2
		if cmd == 'rpos':
			if x[mid] <= x[j] + k:
				pos = mid
				return self.bsearch(mid + 1, right, j, x, k, pos, cmd)
			else:
				return self.bsearch(left, mid - 1, j, x, k, pos, cmd)
		elif x[mid] >= x[j] - k:
			pos = mid
			return self.bsearch(left, mid - 1, j, x, k, pos, cmd)
		else:
			return self.bsearch(mid + 1, right, j, x, k, pos, cmd)

	def solve(self):
		R = stdin.readline
		W = stdout.write
		ans = []
		for i in range(int(input())):
			(n, k) = [int(temp) for temp in R().split()]
			x = [int(temp) for temp in R().split()]
			y = [int(temp) for temp in R().split()]
			x.sort()
			rpos = {}
			for j in range(n):
				rpos[j] = self.bsearch(j, n - 1, j, x, k, j, 'rpos')
			rmx = {}
			rmx[n - 1] = 1
			for j in range(n - 2, -1, -1):
				rmx[j] = max(rmx[j + 1], rpos[j] - j + 1)
			mx = 1
			for j in range(n - 1):
				mx = max(mx, rpos[j] - j + 1 + (rmx[rpos[j] + 1] if rpos[j] + 1 < n else 0))
			ans += [str(mx)]
		W('\n'.join(ans))

def main():
	s = SOLVE()
	s.solve()
main()


t = int(input())
for test in range(t):
	(n, k) = map(int, input().split())
	points = []
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	for i in range(n):
		points.append([x[i], y[i]])
	points.sort()
	(l, r) = (0, 0)
	lrs = []
	while l < n:
		r = max(r, l)
		while r < n and points[r][0] - points[l][0] <= k:
			r += 1
		lrs.append(r - l)
		l += 1
	(l, r) = (0, 0)
	rrs = []
	points.reverse()
	while l < n:
		r = max(r, l)
		while r < n and points[l][0] - points[r][0] <= k:
			r += 1
		rrs.append(r - l)
		l += 1
	rrs.reverse()
	prer = [0]
	for i in range(len(lrs) - 1, -1, -1):
		prer.append(max(prer[-1], lrs[i]))
	ans = 0
	prer.reverse()
	for i in range(n):
		ans = max(rrs[i] + prer[i + 1], ans)
	print(ans)


import sys
import math
import heapq
import collections

def inputnum():
	return int(input())

def inputnums():
	return map(int, input().split())

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

def inputstring():
	return [x for x in input()]

def inputstringnum():
	return [ord(x) - ord('a') for x in input()]

def inputmatrixchar(rows):
	arr2d = [[j for j in input().strip()] for i in range(rows)]
	return arr2d

def inputmatrixint(rows):
	arr2d = []
	for _ in range(rows):
		arr2d.append([int(i) for i in input().split()])
	return arr2d
t = int(input())
for q in range(t):
	(n, k) = inputnums()
	x = inputlist()
	y = inputlist()
	x.sort()
	j = n - 1
	l = [0] * n
	r = [0] * n
	for i in reversed(range(n)):
		while x[j] - x[i] > k:
			j -= 1
		r[i] = j - i + 1
		if i + 1 < n:
			r[i] = max(r[i], r[i + 1])
	j = 0
	for i in range(n):
		while x[i] - x[j] > k:
			j += 1
		l[i] = i - j + 1
		if i > 0:
			l[i] = max(l[i], l[i - 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, l[i] + r[i + 1])
	print(ans)


T = int(input())
for case in range(T):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	suf = [0 for i in range(n + 2)]
	ans = [0 for i in range(n + 2)]
	x.sort()
	j = 0
	for i in range(n):
		while j < n and x[j] <= x[i] + k:
			j += 1
		ans[i] = j - i
	for i in range(n - 1, -1, -1):
		suf[i] = max(ans[i], suf[i + 1])
	mx = 0
	for i in range(n):
		mx = max(mx, ans[i] + suf[min(n, ans[i] + i)])
	print(mx)


def solve(n, k, x, y):
	x = sorted(x)
	l = [0] * n
	r = [0] * n
	ptr = n - 1
	for i in range(n - 1, -1, -1):
		while x[ptr] - x[i] > k:
			ptr -= 1
		r[i] = ptr - i + 1
		if i + 1 < n:
			r[i] = max(r[i], r[i + 1])
	ptr = 0
	for i in range(n):
		while x[i] - x[ptr] > k:
			ptr += 1
		l[i] = i - ptr + 1
		if i > 0:
			l[i] = max(l[i], l[i - 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, l[i] + r[i + 1])
	print(ans)
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	solve(n, k, x, y)


import sys
import math
from collections import defaultdict, Counter
input = sys.stdin.readline

def print(x):
	sys.stdout.write(str(x) + '\n')
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	pre = [1] * n
	suf = [1] * n
	start = 0
	for j in range(1, n):
		if x[j] - x[start] <= k:
			pre[j] = pre[j - 1] + 1
		else:
			pre[j] = pre[j - 1]
			start += 1
	start = n - 1
	for j in range(n - 2, -1, -1):
		if abs(x[j] - x[start]) <= k:
			suf[j] = suf[j + 1] + 1
		else:
			suf[j] = suf[j + 1]
			start -= 1
	ans = 1
	for j in range(n - 1):
		ans = max(ans, pre[j] + suf[j + 1])
	print(ans)


def is_ok(X, K, i, mid):
	if X[mid] - X[i] <= K:
		return True
	else:
		return False

def binary_search(X, K, i):
	ng = len(X)
	ok = i
	while abs(ok - ng) > 1:
		mid = ng + (ok - ng) // 2
		if is_ok(X, K, i, mid):
			ok = mid
		else:
			ng = mid
	return ok

def is_ok2(X, K, i, mid):
	if X[mid] < X[i] - K:
		return True
	else:
		return False

def binary_search2(X, K, i):
	ng = i
	ok = 0
	while abs(ok - ng) > 1:
		mid = ng + (ok - ng) // 2
		if is_ok2(X, K, i, mid):
			ok = mid
		else:
			ng = mid
	return ok

def main():
	T = int(input())
	for _ in range(T):
		(N, K) = (int(i) for i in input().split())
		X = [int(i) for i in input().split()]
		_ = [int(i) for i in input().split()]
		X.sort()
		count = [0] * N
		for i in range(N):
			ret = binary_search(X, K, i)
			count[i] = ret - i + 1
		ans = count[0]
		count_max = [0] * N
		count_max[0] = count[0]
		for i in range(1, N):
			cur = count[i]
			if X[i] - X[0] <= K:
				cur += i
			else:
				j = binary_search2(X, K, i)
				cur += count_max[j]
			ans = max(ans, cur)
			count_max[i] = max(count_max[i - 1], count[i])
		print(ans)
main()


from sys import stdin, stdout
from math import gcd, sqrt, factorial, pi
from collections import deque, defaultdict
input = stdin.readline
R = lambda : map(int, input().split())
I = lambda : int(input())
S = lambda : input().rstrip('\n')
L = lambda : list(R())
P = lambda x: stdout.write(x)
lcm = lambda x, y: x * y // gcd(x, y)
hg = lambda x, y: (y + x - 1) // x * x
pw = lambda x: 1 if x == 1 else 1 + pw(x // 2)
chk = lambda x: chk(x // 2) if not x % 2 else True if x == 1 else False
sm = lambda x: (x ** 2 + x) // 2
N = 10 ** 9 + 7

def binary(l, r, a, k):
	ans = 0
	val = a[l]
	while l <= r:
		m = (l + r) // 2
		if a[m] - val <= k:
			ans = max(ans, m - i + 1)
			l = m + 1
		else:
			r = m - 1
	return ans
for _ in range(I()):
	(n, k) = R()
	a = sorted(R())
	R()
	v = []
	for i in range(n):
		v += (binary(i, n - 1, a, k),)
	dp = [0]
	m = 0
	for i in range(n):
		m = max(m, v[-1 - i])
		dp += (m,)
	dp.reverse()
	ans = 0
	for (j, i) in enumerate(v):
		ans = max(ans, i + dp[j + i])
	print(ans)


import math

def printDivisors(n):
	list = []
	ans = []
	for i in range(1, int(math.sqrt(n) + 1)):
		if n % i == 0:
			if n / i == i:
				ans.append(i)
			else:
				ans.append(i)
				list.append(int(n / i))
	for i in list[::-1]:
		ans.append(i)
	return ans

def sumofdigits(n):
	sm = 0
	while n > 0:
		sm += n % 10
		n = n // 10
	return sm

def listofDigits(n):
	l = []
	while n > 0:
		l.append(n % 10)
		n = n // 10
	l.reverse()
	return l
T = int(input())
for t in range(T):
	(n, k) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	X.sort()
	mx_till = 1
	(low1, low2) = (0, 1)
	(high1, high2) = (0, 1)
	max_front = [1]
	max_reverse = [1]
	net_max = 1
	while high1 < n - 1:
		if high1 < n - 1 and X[high1 + 1] - X[low1] <= k:
			high1 += 1
			mx_till = max(high1 - low1 + 1, mx_till)
			max_front.append(mx_till)
		else:
			low1 += 1
	X.reverse()
	(low1, high1) = (0, 0)
	mx_till = 1
	while high1 < n - 1:
		if high1 < n - 1 and abs(X[high1 + 1] - X[low1]) <= k:
			high1 += 1
			mx_till = max(high1 - low1 + 1, mx_till)
			max_reverse.append(mx_till)
		else:
			low1 += 1
	max_reverse.reverse()
	for i in range(n - 1):
		net_max = max(net_max, max_front[i] + max_reverse[i + 1])
	print(net_max)


z = lambda : map(int, input().split())
r = range
p = print
for _ in r(int(input())):
	(n, k) = z()
	l = sorted(list(z()))
	z()
	if n < 3:
		p(n)
		continue
	a = i = 0
	b = m = e = o = 1
	f = 2
	c = [0, 1]
	d = [1]
	while a < n:
		while b < n and l[b] <= l[a] + k:
			b += 1
			m = max(m, b - a)
			c += [m]
		a += 1
	while e < n + 1:
		while f < n + 1 and l[-f] >= l[-e] - k:
			f += 1
			o = max(o, f - e)
			d += [o]
		e += 1
	p(max((c[i] + d[-i - 1] for i in r(n))))


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x_coordinates = list(map(int, input().split()))
	x_coordinates.sort()
	input()
	if n == 1:
		print(1)
		continue
	L = 0
	R = 0
	length = 0
	points = 0
	platform_points = []
	while True:
		length = x_coordinates[R] - x_coordinates[L]
		if length <= k:
			points = R - L + 1
			R += 1
			if R >= n:
				platform_points.append((L, points))
				break
		else:
			platform_points.append((L, points))
			while x_coordinates[R] - x_coordinates[L] > k:
				L += 1
	maximum_points_to_the_right = [1] * n
	for (i, points) in platform_points:
		maximum_points_to_the_right[i] = points
	for i in range(n - 1, 0, -1):
		maximum_points_to_the_right[i - 1] = max(maximum_points_to_the_right[i - 1], maximum_points_to_the_right[i])
	for i in range(n - 1):
		maximum_points_to_the_right[i + 1] = max(maximum_points_to_the_right[i + 1], maximum_points_to_the_right[i] - 1)
	L = n - 1
	R = n - 1
	length = 0
	points = 0
	platform_points = []
	while True:
		length = x_coordinates[R] - x_coordinates[L]
		if length <= k:
			points = R - L + 1
			L -= 1
			if L < 0:
				platform_points.append((R, points))
				break
		else:
			platform_points.append((R, points))
			while x_coordinates[R] - x_coordinates[L] > k:
				R -= 1
	maximum_points_to_the_left = [1] * n
	for (i, points) in platform_points:
		maximum_points_to_the_left[i] = points
	for i in range(n - 1):
		maximum_points_to_the_left[i + 1] = max(maximum_points_to_the_left[i + 1], maximum_points_to_the_left[i])
	for i in range(n - 1, 0, -1):
		maximum_points_to_the_left[i - 1] = max(maximum_points_to_the_left[i - 1], maximum_points_to_the_left[i] - 1)
	s = []
	for i in range(n - 1):
		x = maximum_points_to_the_left[i] + maximum_points_to_the_right[i + 1]
		s.append(x)
	print(max(s))


import sys
import math
input = sys.stdin.readline

def inInt():
	return int(input())

def inStr():
	return input().strip('\n')

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

def inSList():
	return input().split()

def l2hist(l):
	m = {}
	for i in range(len(l)):
		if l[i] not in m:
			m[l[i]] = 0
		m[l[i]] += 1
	return m

def m2l(m):
	return list(sorted(m.items(), key=lambda x: x[0]))

def solve(k, n, x, y):
	m = l2hist(x)
	A = m2l(m)
	N = len(A)
	R = [A[0][1] for i in range(N)]
	B = [1 for i in range(N)]
	p = 0
	w = A[0][1]
	for i in range(1, N):
		w = w + A[i][1]
		while A[i][0] - A[p][0] > k:
			w = w - A[p][1]
			p = p + 1
		R[i] = w
		B[i] = i - p + 1
	ma = R[0]
	S = []
	for i in range(N):
		ma = max(ma, R[i])
		S.append(ma)
	D = [S[0]]
	for i in range(1, N):
		v = max(D[i - 1], R[i] + (S[i - B[i]] if i - B[i] >= 0 else 0))
		D.append(v)
	print(D[N - 1])
tasks = inInt()
for t in range(tasks):
	n_k = inIList()
	n = n_k[0]
	k = n_k[1]
	x = inIList()
	y = inIList()
	solve(k, n, x, y)


from sys import stdin
input = lambda : stdin.readline().strip()
from math import ceil, sqrt, factorial, gcd
from collections import deque
from bisect import bisect_left
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	o = list(map(int, input().split()))
	x.sort()
	a = [0 for i in range(n)]
	b = list(a)
	for i in range(n):
		t = bisect_left(x, x[i] - k)
		a[i] = max(a[i - 1], i - t + 1)
		if t > 0:
			b[i] = max(b[i - 1], i - t + 1 + a[t - 1])
		else:
			b[i] = max(b[i - 1], i - t + 1)
	print(max(b[-1], a[-1]))


from collections import Counter
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	if n <= 2:
		print(n)
		continue
	x.sort()
	l = [0] * n
	r = [0] * n
	j = 0
	for i in range(n):
		while x[i] - x[j] > k:
			j += 1
		l[i] = max(l[i - 1] if i != 0 else 0, i - j + 1)
	j = n - 1
	for i in range(n - 1, -1, -1):
		while x[j] - x[i] > k:
			j -= 1
		r[i] = max(r[i + 1] if i != n - 1 else 0, j - i + 1)
	print(max((l[i] + r[i + 1] for i in range(n - 1))))


import os
import sys
import math
from io import BytesIO, IOBase
from fractions import Fraction
import collections
from itertools import permutations
import threading
from collections import defaultdict
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')
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	j1 = n - 2
	j2 = 1
	pre = [0] * n
	suf = [0] * n
	for i in range(n):
		while j2 < n and x[j2] - x[i] <= k:
			j2 += 1
		suf[i] = j2 - i
	for i in range(n - 2, -1, -1):
		suf[i] = max(suf[i], suf[i + 1])
	for i in range(n - 1, -1, -1):
		while j1 >= 0 and x[i] - x[j1] <= k:
			j1 -= 1
		pre[i] = i - j1
	for i in range(1, n):
		pre[i] = max(pre[i], pre[i - 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, pre[i] + suf[i + 1])
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = [int(zz) for zz in input().split()]
	x = [int(zz) for zz in input().split()]
	y = [int(zz) for zz in input().split()]
	x.sort()
	l = x[0]
	r = x[-1]
	if k * 2 + 1 >= r - l:
		print(n)
		continue
	else:
		cnts = [-1 for __ in range(len(x))]
		j = 0
		for i in range(len(x)):
			while x[i] - x[j] > k:
				j += 1
			cnts[i] = i - j + 1
		mr = [0 for __ in range(len(x))]
		for i in range(len(x) - 1, -1, -1):
			mr[i] = cnts[i]
			if i + 1 < len(x):
				mr[i] = max(mr[i], mr[i + 1])
		ans = 1
		j = 0
		for i in range(len(x)):
			while j < len(x) and x[j] - x[i] <= k:
				j += 1
			if j == len(x):
				break
			ans = max(ans, cnts[i] + mr[j])
		print(ans)


from collections import Counter
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = [*map(int, input().split())]
	y = [*map(int, input().split())]
	a = []
	x = Counter(x)
	pre = []
	for i in x:
		a.append((i, x[i]))
	a.sort()
	(l, r) = (0, 0)
	c = 0
	n = len(a)
	pre2 = [None] * n
	while l < n:
		if r < n and a[r][0] - a[l][0] <= k:
			c += a[r][1]
			r += 1
		else:
			pre.append(c)
			c -= a[l][1]
			l += 1
	k_ = -1
	for i in range(n - 1, -1, -1):
		pre2[i] = max(k_, pre[i])
		k_ = pre2[i]
	(l, r) = (0, 0)
	ans = 0
	while l < n:
		if r < n and a[r][0] - a[l][0] <= k:
			r += 1
			continue
		if r < n:
			ans = max(ans, pre[l] + pre2[r])
			l += 1
		else:
			ans = max(ans, pre[l])
			l += 1
			break
	print(ans)


for t in range(int(input())):
	(n, k) = map(int, input().split())
	a = list(map(int, input().split()))
	b = list(map(int, input().split()))
	l = [0] * (n + 1)
	r = [0] * (n + 1)
	a.sort()
	i = 0
	for j in range(n):
		while a[j] - a[i] > k:
			i += 1
		l[j + 1] = j - i + 1
		l[j + 1] = max(l[j + 1], l[j])
	i = n - 1
	for j in range(n - 1, -1, -1):
		while a[i] - a[j] > k:
			i -= 1
		r[j] = i - j + 1
		r[j] = max(r[j], r[j + 1])
	maxi = 0
	for i in range(n + 1):
		maxi = max(l[i] + r[i], maxi)
	print(maxi)


import sys

class ETwoPlatforms:

	def solve(self, tc=0):
		for _ in range(int(input())):
			(n, k) = [int(_) for _ in input().split()]
			x = [int(_) for _ in input().split()]
			y = [int(_) for _ in input().split()]
			x.sort()
			ans = 0
			(s, e) = (0, 1)
			mx = 1
			n = len(x)
			pre = [0] * (n + 1)
			pre[1] = 1
			last = -1
			while e < n:
				while e < n and x[e] - x[s] <= k:
					pre[e] = max(pre[last], e - s)
					last = e
					e += 1
				pre[e] = max(pre[last], e - s)
				last = e
				s += 1
			post = [0] * n
			post[-1] = 1
			(s, e) = (n - 1, n - 2)
			last = 0
			while e >= 0:
				while e >= 0 and x[s] - x[e] <= k:
					post[e] = max(post[last], s - e + 1)
					last = e
					e -= 1
				e += 1
				post[e] = max(post[last], s - e + 1)
				last = e
				e -= 1
				s -= 1
			ans = 0
			for i in range(n):
				ans = max(ans, pre[i] + post[i])
			ans = max(ans, pre[n])
			print(ans)
solver = ETwoPlatforms()
input = sys.stdin.readline
solver.solve()


tc = int(input())
for _ in range(tc):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	input()
	if n == 1:
		print(1)
		continue
	x.sort()
	j = 0
	a = []
	for i in range(n):
		while j + 1 < n and x[j + 1] - x[i] <= k:
			j += 1
		a.append(j - i + 1)
	for i in range(n - 2, -1, -1):
		a[i] = max(a[i], a[i + 1])
	j = n - 1
	b = []
	for i in range(n - 1, -1, -1):
		while j - 1 >= 0 and x[i] - x[j - 1] <= k:
			j -= 1
		b.append(i - j + 1)
	b.reverse()
	for i in range(1, n):
		b[i] = max(b[i], b[i - 1])
	print(max((a[i + 1] + b[i] for i in range(n - 1))))


from bisect import bisect_left, bisect_right

def solve():
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	dp = [0] * len(x)
	ans = 0
	for i in range(len(x)):
		st = x[i] - k
		st_idx = bisect_left(x, st)
		cur_save = i - st_idx + 1
		dp[i] = cur_save if i == 0 else max(cur_save, dp[i - 1])
		f_idx = bisect_right(x, st - 1)
		if x[f_idx] >= st:
			f_idx -= 1
		if f_idx >= 0:
			assert x[f_idx] < st
		prev_save = dp[f_idx] if f_idx >= 0 else 0
		ans = max(ans, cur_save + prev_save)
	print(ans)
T = int(input())
for _ in range(T):
	solve()


from math import inf, floor, log

def main():

	def solve():

		def createSparseTable():
			sparseTable = [[i] for i in range(n)]
			for j in range(1, floor(log(n, 2)) + 1):
				for i in range(n):
					length = 1 << j
					if i + length - 1 > n - 1:
						break
					sparseTable[i].append(0)
					indexOfMax1 = sparseTable[i][j - 1]
					indexOfMax2 = sparseTable[i + length // 2][j - 1]
					if savedByBar[indexOfMax1] > savedByBar[indexOfMax2]:
						sparseTable[i][j] = indexOfMax1
					else:
						sparseTable[i][j] = indexOfMax2
			return sparseTable

		def getMaxSavedStartingAt(start):
			rangeLength = n - start
			checkLength = floor(log(rangeLength, 2))
			indexOfMax1 = sparseTable[start][checkLength]
			numbersLeft = rangeLength - (1 << checkLength)
			indexOfMax2 = sparseTable[start + numbersLeft][checkLength]
			return max(savedByBar[indexOfMax1], savedByBar[indexOfMax2])

		def find(low, xBoundary, mode):
			high = n - 1
			while low < high:
				mid = (high + low) // 2
				if x[mid] > xBoundary:
					high = mid - 1
				else:
					low = mid + 1
			mid = (high + low) // 2
			if mode == 1:
				return mid if x[mid] <= xBoundary else max(mid - 1, 0)
			else:
				return mid if x[mid] > xBoundary else mid + 1
		(n, k) = [int(x) for x in input().split()]
		x = [int(x) for x in input().split()]
		x.sort()
		input()
		savedByBar = [-inf] * n
		for leftmost in range(n):
			rightmost = find(leftmost, x[leftmost] + k, 1)
			savedByBar[leftmost] = max(rightmost - leftmost + 1, savedByBar[leftmost])
		sparseTable = createSparseTable()
		maxSaved = 1
		for leftBar in range(n - 1):
			firstNotOverlapping = find(leftBar, x[leftBar] + k, 2)
			if firstNotOverlapping > n - 1:
				maxSaved = max(getMaxSavedStartingAt(leftBar), maxSaved)
				break
			savedByRightBar = getMaxSavedStartingAt(firstNotOverlapping)
			maxSaved = max(savedByBar[leftBar] + savedByRightBar, maxSaved)
			if maxSaved == n:
				break
		print(maxSaved)
	t = int(input())
	for i in range(t):
		solve()
main()


from sys import stdin, stdout

def INPUT():
	return list((int(i) for i in stdin.readline().split()))

def inp():
	return stdin.readline()

def out(x):
	return stdout.write(x)
import math
import random
J = int(1000000000.0) + 7
from bisect import bisect_left
for _ in range(int(input())):
	(n, k) = INPUT()
	A = INPUT()
	B = INPUT()
	A.sort()
	P = {}
	for e in A:
		if e in P:
			P[e] += 1
		else:
			P[e] = 1
	ans = 0
	X = []
	count = []
	for ele in P:
		X.append(ele)
		count.append(P[ele])
	sumc = [0] * len(count)
	sumc[0] = count[0]
	for i in range(1, len(count)):
		sumc[i] = sumc[i - 1] + count[i]
	dp1 = [0] * len(count)
	dp1[0] = count[0]
	for i in range(1, len(count)):
		ind = bisect_left(X, X[i] - k)
		if ind == 0:
			dp1[i] = max(dp1[i - 1], sumc[i])
		else:
			dp1[i] = max(sumc[i] - sumc[ind - 1], dp1[i - 1])
	dp2 = [0] * len(count)
	dp2[0] = count[0]
	for i in range(1, len(count)):
		ind = bisect_left(X, X[i] - k)
		if ind == 0:
			first = 0
		else:
			first = sumc[ind - 1]
		last = sumc[i]
		if ind != 0:
			dp2[i] = max(dp2[i - 1], last - first + dp1[ind - 1])
		else:
			dp2[i] = sumc[i]
	print(dp2[-1])


import sys
from collections import Counter
input = sys.stdin.readline

def calc(num):
	low = 0
	high = n
	while low < high:
		mid = (low + high) // 2
		if a[mid][0] > num:
			high = mid - 1
		elif a[mid][0] < num:
			low = mid + 1
		else:
			return mid
	if low < len(a) and a[low][0] <= num:
		return low
	else:
		return low - 1

class SegTree(object):

	def __init__(self, n, arr):
		self.n = n
		self.arr = arr
		self.tree = [0 for i in range(2 * n)]

	def construct(self):
		for i in range(self.n):
			self.tree[self.n + i] = self.arr[i]
		for i in range(self.n - 1, 0, -1):
			self.tree[i] = self.function(self.tree[2 * i], self.tree[2 * i + 1])

	def update(self, index, value):
		start = index + self.n
		self.tree[start] = value
		start = start // 2
		while start > 0:
			self.tree[start] = self.function(self.tree[2 * start], self.tree[2 * start + 1])
			start = start // 2

	def calc(self, low, high):
		low += self.n
		high += self.n
		ans = 0
		while low < high:
			if low % 2:
				ans = self.function(ans, self.tree[low])
				low += 1
			if high % 2:
				high -= 1
				ans = self.function(ans, self.tree[high])
			low = low // 2
			high = high // 2
		return ans

	def function(self, a, b):
		return max(a, b)
final = []
for nt in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	if max(x) - min(x) <= 2 * k:
		final.append(n)
		continue
	c = Counter(x)
	a = []
	for i in c:
		a.append([i, c[i]])
	a.sort()
	p = [a[0][1]]
	n = len(a)
	for i in range(1, n):
		p.append(p[-1] + a[i][1])
	for i in range(n):
		if a[i][0] - a[0][0] > k:
			ind = i - 1
			break
	s = [(p[ind], 0, ind)]
	m = p[ind]
	nums = [p[ind]]
	for i in range(1, n):
		j = calc(a[i][0] + k)
		s.append((p[j] - p[i - 1], i, j))
		nums.append(p[j] - p[i - 1])
		m = max(m, s[-1][0])
	st = SegTree(len(nums), nums)
	st.construct()
	prev = 0
	nxt = 0
	m = 0
	ans = s[0][0]
	for i in range(len(s)):
		while nxt < len(s) and s[nxt][1] <= s[i][2]:
			nxt += 1
		while s[prev][2] < s[i][1]:
			m = max(m, s[prev][0])
			prev += 1
		ans = max(ans, s[i][0] + max(m, st.calc(nxt, len(s))))
	final.append(ans)
for i in final:
	print(i)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	arr = list(map(int, input().split()))
	y = list(map(int, input().split()))
	arr.sort()
	i = j = 0
	end = [0] * n
	start = [0] * n
	while j < n:
		if arr[j] - arr[i] <= k:
			if j:
				end[j] = max(end[j - 1], j - i + 1)
			else:
				end[j] = j - i + 1
			j += 1
		else:
			i += 1
	i = j = n - 1
	while i >= 0:
		if arr[j] - arr[i] <= k:
			if i == n - 1:
				start[i] = j - i + 1
			else:
				start[i] = max(start[i + 1], j - i + 1)
			i -= 1
		else:
			j -= 1
	ans = 1
	for i in range(n - 1):
		ans = max(ans, start[i + 1] + end[i])
	print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for rrr in range(t):
	(n, k) = list(map(int, input().split()))
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	pl = []
	i = 0
	j = 0
	tmp = []
	for j in range(n):
		if x[j] - x[i] > k:
			pl.append((i, j - 1))
			while i < len(x) and x[j] - x[i] > k:
				i += 1
		if j == n - 1:
			while i < len(x) and x[j] - x[i] > k:
				i += 1
			pl.append((i, j))
	rr = list(pl)
	rr.sort(key=lambda x: x[1])
	if len(x) < 3:
		print(len(x))
	else:
		best = 0
		ans = 0
		j = 0
		for i in range(len(pl)):
			(l, r) = (pl[i][0], pl[i][1])
			if l > rr[j][1]:
				best = max(best, rr[j][1] - rr[j][0] + 1)
			if l <= rr[j][1]:
				ans = max(ans, r - rr[j][0] + 1)
			ans = max(ans, r - l + 1 + best)
			while rr[j][1] < l:
				if l > rr[j][1]:
					best = max(best, rr[j][1] - rr[j][0] + 1)
				if l <= rr[j][1]:
					ans = max(ans, r - rr[j][0] + 1)
				ans = max(ans, r - l + 1 + best)
				j += 1
			if l > rr[j][1]:
				best = max(best, rr[j][1] - rr[j][0] + 1)
			if l <= rr[j][1]:
				ans = max(ans, r - rr[j][0] + 1)
			ans = max(ans, r - l + 1 + best)
		if False:
			if rrr == 251:
				print(n, k)
				print(pl)
				print(rr)
				print(x)
				print(ans)
		else:
			print(ans)


import sys
input = sys.stdin.readline
t = int(input())
for ii in range(t):
	(n, k) = map(int, input().split())
	x = [int(i) for i in input().split()]
	y = [int(i) for i in input().split()]
	x.sort()
	(i, j) = (0, 0)
	(ans, tmp) = (0, 1)
	(end, start) = (0, 0)
	store = []
	while j < n:
		if x[j] - x[i] <= k:
			j += 1
			if j < n and x[j] - x[i] <= k:
				tmp += 1
		else:
			j -= 1
			store.append((tmp, i, j))
			tmp -= 1
			i += 1
	store.append((tmp, i, j - 1))
	store.sort(reverse=True)
	start = [0] * (n + 1)
	for i in range(len(store)):
		start[store[i][1]] = max(start[store[i][1]], store[i][0])
	for i in range(n - 2, -1, -1):
		start[i] = max(start[i + 1], start[i])
	ans = 0
	for i in range(n):
		if start[i] == 0:
			start[i] = max(0, start[i - 1] - 1)
	for i in store:
		ans = max(ans, i[0] + start[i[2] + 1])
	sys.stdout.write(str(ans) + '\n')


import sys, os
from io import BytesIO, IOBase
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, 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')
(stdin, stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
mod = pow(10, 9) + 7
mod2 = 998244353

def inp():
	return stdin.readline().strip()

def iinp():
	return int(inp())

def out(var, end='\n'):
	stdout.write(str(var) + '\n')

def outa(*var, end='\n'):
	stdout.write(' '.join(map(str, var)) + end)

def lmp():
	return list(mp())

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

def l1d(n, val=0):
	return [val for i in range(n)]

def l2d(n, m, val=0):
	return [l1d(m, val) for j in range(n)]

def ceil(a, b):
	return (a + b - 1) // b
S1 = 'abcdefghijklmnopqrstuvwxyz'
S2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

def isprime(x):
	if x <= 1:
		return False
	if x in (2, 3):
		return True
	if x % 2 == 0:
		return False
	for i in range(3, int(sqrt(x)) + 1, 2):
		if x % i == 0:
			return False
	return True
for _ in range(iinp()):
	(n, k) = mp()
	(x, _) = (lmp(), lmp())
	x.append(-inf)
	x.sort()
	cnt = l1d(n + 1)
	mx = l1d(n + 1)
	ans = 0
	for i in range(1, n + 1):
		ind = bl(x, x[i] - k)
		cnt[i] = 1 + i - ind
		mx[i] = max(mx[i - 1], cnt[i])
		ans = max(ans, cnt[i] + mx[ind - 1])
	print(ans)


from sys import stdin
from collections import Counter
N = int(stdin.readline())
for case in range(N):
	(pointcount, platformlength) = map(int, stdin.readline().split())
	xcoords = [int(i) for i in stdin.readline().split()]
	ycords = stdin.readline()
	sortedx = sorted(xcoords)
	left = []
	right = []
	pointer = 1
	sol = 0
	j = 0
	if pointcount == 1:
		print(1)
		continue
	for i in range(pointcount):
		count = 0
		while sortedx[i] - sortedx[j] > platformlength:
			j += 1
		left.append(i - j + 1)
		if i > 0:
			left[i] = max(left[i], left[i - 1])
	j = pointcount - 1
	for i in range(pointcount - 1, -1, -1):
		while sortedx[j] - sortedx[i] > platformlength:
			j -= 1
		right.append(j - i + 1)
		if i < pointcount - 1:
			right[pointer] = max(right[pointer], right[pointer - 1])
			pointer += 1
	for i in range(pointcount - 1):
		sol = max(sol, left[i] + right[-i - 2])
	print(sol)


from bisect import bisect_left as bl
from bisect import bisect_right as br
from heapq import heappush, heappop, heapify
import math
from collections import *
from functools import reduce, cmp_to_key
import sys
input = sys.stdin.readline
from itertools import accumulate
from functools import lru_cache
M = mod = 998244353

def factors(n):
	return sorted(set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0))))

def inv_mod(n):
	return pow(n, mod - 2, mod)

def li():
	return [int(i) for i in input().rstrip('\n').split()]

def st():
	return input().rstrip('\n')

def val():
	return int(input().rstrip('\n'))

def li2():
	return [i for i in input().rstrip('\n')]

def li3():
	return [int(i) for i in input().rstrip('\n')]

class Node:

	def __init__(self, s, e):
		self.start = s
		self.end = e
		self.val = 0
		self.left = None
		self.right = None

def build(nums, l, r):
	if l == r:
		temp = Node(l, l)
		temp.val = nums[l]
	else:
		mid = l + r >> 1
		temp = Node(l, r)
		temp.left = build(nums, l, mid)
		temp.right = build(nums, mid + 1, r)
		temp.val = max(temp.left.val, temp.right.val)
	return temp

def update(root, start, value):
	if root.start == start == root.end:
		root.val = value
	elif root.start <= start and root.end >= start:
		update(root.left, start, value)
		update(root.right, start, value)
		root.val = max(root.left.val, root.right.val)

def query(root, start, end):
	if root.start >= start and root.end <= end:
		return root.val
	elif root.start > end or root.end < start:
		return -float('inf')
	else:
		temp1 = query(root.left, start, end)
		temp2 = query(root.right, start, end)
		return max(temp1, temp2)
for _ in range(val()):
	(n, k) = li()
	l = li()
	y = li()
	l.sort()
	dp = [0] * (n + 1)
	for i in range(n - 1, -1, -1):
		curright = br(l, l[i] + k)
		totnow = curright - i
		dp[i] = totnow
	root = build(dp, 0, n)
	for i in range(n):
		curright = br(l, l[i] + k)
		dp[i] += query(root, curright, n)
	print(max(dp))


from math import ceil
from collections import deque
for _ in range(int(input())):
	(n, k) = [int(i) for i in input().split()]
	x = [int(i) for i in input().split()]
	y = [int(i) for i in input().split()]
	x.sort()
	a = []
	for i in x:
		a.append((i, 1))
		a.append((i - k, 0))
	a.sort()
	s = []
	sav = 0
	for i in a:
		if i[1]:
			sav -= 1
		else:
			sav += 1
		s.append((i[0], sav))
	s.sort()
	mx = [[i[0], 0] for i in s]
	t = 0
	for i in range(len(s) - 1, -1, -1):
		t = max(s[i][1], t)
		mx[i][1] = t
	if t == n:
		print(n)
		continue
	mx.append((9999999999, 0))
	ans = mx[0][1]
	j = 0
	for i in range(len(s)):
		while mx[j][0] <= s[i][0] + k and j < len(s):
			j += 1
		ans = max(ans, s[i][1] + mx[j][1])
	print(ans)


for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	(left, right) = ([0] * n, [0] * n)
	first = 0
	for i in range(n):
		while first < n and x[first] - x[i] <= k:
			first += 1
		right[i] = first - i
	second = n - 1
	for i in range(n - 1, -1, -1):
		while second >= 0 and x[i] - x[second] <= k:
			second -= 1
		left[i] = i - second
	(mx, ans) = (0, 0)
	for i in range(n):
		ans = max(ans, mx + right[i])
		mx = max(mx, left[i])
	print(ans)


def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x - 1)

def lower_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer

def upper_bound(li, num):
	answer = -1
	start = 0
	end = len(li) - 1
	while start <= end:
		middle = (end + start) // 2
		if li[middle] <= num:
			answer = middle
			start = middle + 1
		else:
			end = middle - 1
	return answer

def abs(x):
	return x if x >= 0 else -x

def binary_search(li, val, lb, ub):
	ans = 0
	while lb <= ub:
		mid = (lb + ub) // 2
		if li[mid] > val:
			ub = mid - 1
		elif val > li[mid]:
			lb = mid + 1
		else:
			ans = 1
			break
	return ans

def kadane(x):
	sum_so_far = 0
	current_sum = 0
	for i in x:
		current_sum += i
		if current_sum < 0:
			current_sum = 0
		else:
			sum_so_far = mpos(sum_so_far, current_sum)
	return sum_so_far

def pref(li):
	pref_sum = [0]
	for i in li:
		pref_sum.append(pref_sum[-1] + i)
	return pref_sum

def graph(n, m):
	adj = dict()
	for i in range(1, n + 1):
		adj.setdefault(i, 0)
	for i in range(m):
		(a, b) = map(int, input().split())
		adj[a] += 1
		adj[b] += 1
	return adj
import sys
import threading
from math import *
sys.setrecursionlimit(300000)
threading.stack_size(10 ** 8)
po = int(log(10 ** 18)) + 2
li = []
for i in range(po):
	li.append(3 ** i)
li = li[::-1]
s = sum(li)
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort(reverse=True)
	j = n - 1
	l = [0] * n
	r = [0] * (n + 1)
	for i in range(n - 1, -1, -1):
		while x[i] - x[j] > k:
			j -= 1
		r[i] = j - i + 1
		if i < n - 1:
			r[i] = max(r[i], r[i + 1])
	j = 0
	for i in range(n):
		while x[j] - x[i] > k:
			j += 1
		l[i] = i - j + 1
		if i > 0:
			l[i] = max(l[i], l[i - 1])
	ans = 0
	for i in range(n):
		ans = max(ans, r[i + 1] + l[i])
	print(ans)


import sys
from bisect import bisect_right as br
input = sys.stdin.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	xs = list(map(int, input().split()))
	input()
	xs.sort()
	lmax = [0] * (n + 1)
	rmax = [0] * (n + 1)
	for l in range(n):
		r = br(xs, xs[l] + k)
		lmax[l] = r - l
		rmax[r] = max(rmax[r], r - l)
	for i in range(n, 0, -1):
		lmax[i - 1] = max(lmax[i - 1], lmax[i])
	for i in range(n):
		rmax[i + 1] = max(rmax[i + 1], rmax[i])
	res = 0
	for i in range(n + 1):
		res = max(res, lmax[i] + rmax[i])
	print(res)


for t in range(int(input())):
	(n, k) = map(int, input().split())
	x = [int(i) for i in input().split()]
	y = input()
	x.sort()
	mx = []
	price = []
	cur = 0
	ptr = 0
	for (p, i) in enumerate(x):
		while ptr < len(x) and x[ptr] - i <= k:
			cur += 1
			ptr += 1
		price.append(cur)
		cur -= 1
	cur = 0
	for (p, i) in enumerate(price):
		cur = max(cur, i)
		mx.append(cur)
	ans = 0
	ptr = 0
	for (p, i) in enumerate(price):
		while x[p] - x[ptr] > k:
			ptr += 1
		if ptr != 0:
			ans = max(ans, mx[ptr - 1] + i)
		else:
			ans = max(ans, i)
	print(ans)


from bisect import bisect_left
for _ in range(int(input())):
	(n, k) = list(map(int, input().split()))
	(nums, _) = (sorted(map(int, input().split())), list(map(int, input().split())))
	if 2 * k >= nums[-1] - nums[0]:
		print(len(nums))
		continue
	f = [[0, 0] for _ in range(n + 1)]
	for i in range(1, n + 1):
		j = bisect_left(nums, nums[i - 1] - k)
		f[i][0] = max(f[i - 1][0], i - j)
		f[i][1] = max(f[i - 1][1], f[j][0] + i - j)
	print(f[n][1])


T = int(input())
while T > 0:
	(n, k) = map(int, input().split())
	xs = list(map(int, input().split()))
	ys = list(map(int, input().split()))
	xs.sort()
	dp1 = [0] * n
	start = 0
	for i in range(n):
		while xs[i] - xs[start] > k:
			start += 1
		dp1[i] = max(dp1[i - 1], i - start + 1)
	start = 0
	dp2 = [0] * n
	for i in range(n):
		while xs[i] - xs[start] > k:
			start += 1
		if start > 0:
			dp2[i] = max(dp2[i - 1], i - start + 1 + dp1[start - 1])
		else:
			dp2[i] = max(dp2[i - 1], i - start + 1)
	res = dp2[-1]
	print(res)
	T -= 1


from bisect import *
I = lambda : map(int, input().split())
(t,) = I()
b = bisect_left
while t:
	t -= 1
	(n, k) = I()
	x = sorted(I())
	I()
	a = q = 0
	m = [n - i - b(x, x[~i] - k) for i in range(n)]
	for i in range(n):
		a = max(a, q + b(x, x[i] + k + 0.5) - i)
		q = max(q, m[~i])
	print(a)


import sys
import bisect
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	cnt = [0] * n
	for i in range(n):
		idx = bisect.bisect_right(x, x[i] + k)
		for j in range(idx - 1, idx + 2):
			if 0 <= j < n and x[i] + k < x[j]:
				idx = j
				break
		idx -= 1
		cnt[i] = min(idx - i + 1, n)
	cnt_max = [cnt[i] for i in range(n)]
	for i in range(n - 1)[::-1]:
		cnt_max[i] = max(cnt_max[i], cnt_max[i + 1])
	ans = 0
	for i in range(n):
		idx = bisect.bisect_right(x, x[i] + k)
		for j in range(idx - 1, idx + 2):
			if 0 <= j < n and x[i] + k < x[j]:
				idx = j
				break
		if idx < n:
			ans = max(ans, cnt[i] + cnt_max[idx])
		else:
			ans = max(ans, cnt[i])
	print(ans)


from os import path
import sys
from heapq import heappush, heappop
from functools import cmp_to_key as ctk
from collections import deque, defaultdict as dd
from bisect import bisect, bisect_left, bisect_right, insort, insort_left, insort_right
from itertools import permutations
from datetime import datetime
from math import ceil, sqrt, log, gcd

def ii():
	return int(input())

def si():
	return input().rstrip()

def mi():
	return map(int, input().split())

def li():
	return list(mi())
abc = 'abcdefghijklmnopqrstuvwxyz'
mod = 1000000007
inf = float('inf')
vow = ['a', 'e', 'i', 'o', 'u']
(dx, dy) = ([-1, 1, 0, 0], [0, 0, 1, -1])

def bo(i):
	return ord(i) - ord('a')
file = 1

def solve():
	for _ in range(ii()):
		(n, k) = mi()
		a = li()
		b = li()
		a.sort()
		ans = []
		for i in range(n):
			x1 = a[i] + k + 1
			r = bisect_left(a, x1)
			ans.append([r - i, r])
		suff = [0] * (n + 1)
		for i in range(n - 1, -1, -1):
			suff[i] = max(suff[i + 1], ans[i][0])
		res = 0
		for i in range(n):
			r = ans[i][1]
			res = max(res, ans[i][0] + suff[r])
		print(res)
if file:
	if path.exists('input.txt'):
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	else:
		input = sys.stdin.readline
solve()


import sys, math, heapq, collections, itertools, bisect
sys.setrecursionlimit(101000)

def solve(n, k, xs, ys):
	xs.sort()
	l = r = 0
	hf = [0] * n
	while l < n:
		while r < n and xs[r] - xs[l] <= k:
			r += 1
		hf[l] = r - l
		l += 1
	sol = 0
	ss = [0] * (n + 1)
	for i in range(n - 1, -1, -1):
		ss[i] = max(ss[i + 1], hf[i])
	for i in range(n):
		curr = hf[i] + (ss[i + hf[i]] if i + hf[i] <= n else 0)
		sol = max(sol, curr)
	return sol
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	xs = list(map(int, input().split()))
	ys = list(map(int, input().split()))
	print(solve(n, k, xs, ys))


import sys, os, io
from math import log, gcd, ceil
from collections import defaultdict as dd, deque, Counter
from heapq import heappush, heappop
from sys import stdin
from bisect import bisect_left, bisect_right
import math

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

def primeFactors(n):
	l = []
	while n % 2 == 0:
		l.append(2)
		n = n / 2
	for i in range(3, int(math.sqrt(n)) + 1, 2):
		while n % i == 0:
			l.append(int(i))
			n = n / i
	if n > 2:
		l.append(n)
	return list(set(l))

def power(x, y, p):
	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 si():
	return input()

def prefix_sum(arr):
	r = [0] * (len(arr) + 1)
	for (i, el) in enumerate(arr):
		r[i + 1] = r[i] + el
	return r

def divideCeil(n, x):
	if n % x == 0:
		return n // x
	return n // x + 1

def ii():
	return int(input())

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

def ws(s):
	sys.stdout.write(s + '\n')

def wi(n):
	sys.stdout.write(str(n) + '\n')

def wia(a):
	sys.stdout.write(' '.join([str(x) for x in a]) + '\n')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
mod = 998244353
t = 1
t = ii()
for _ in range(t):
	(n, k) = li()
	x = li()
	y = li()
	if n == 1:
		print(1)
		continue
	x.sort()
	leftptr = 0
	l = [1] * n
	for i in range(n):
		if x[leftptr] + k < x[i]:
			leftptr += 1
		l[i] = i - leftptr + 1
	rightptr = n - 1
	r = [1] * n
	for i in range(n - 1, -1, -1):
		if x[rightptr] - k > x[i]:
			rightptr -= 1
		r[i] = rightptr - i + 1
	for i in range(1, n):
		l[i] = max(l[i], l[i - 1])
	for i in range(n - 2, -1, -1):
		r[i] = max(r[i], r[i + 1])
	ans = 0
	for i in range(n - 1):
		ans = max(ans, l[i] + r[i + 1])
	print(ans)


import sys as _sys

def main():
	t = int(input())
	for i in range(t):
		(n, k) = _read_ints()
		xs = tuple(_read_ints())
		ys = tuple(_read_ints())
		result = find_max_points_can_save_n(xs, ys, platform_size=k)
		print(result)

def _read_ints():
	return map(int, _sys.stdin.readline().split(' '))

def find_max_points_can_save_n(points_xs, points_ys, platform_size):
	del points_ys
	max_points_can_save = _find_max_range(points_xs, platform_size * 2 + 1)[1]
	ranges = _compute_ranges(points_xs, platform_size)
	first_ranges = list(ranges)
	second_ranges = sorted(ranges, key=lambda range_: range_[1], reverse=True)
	i_second = 0
	for ((first_x, last_x), points_saved) in first_ranges:
		while i_second < len(second_ranges) and second_ranges[i_second][0][0] <= last_x:
			i_second += 1
		if i_second >= len(second_ranges):
			break
		points_saved_second = second_ranges[i_second][1]
		max_points_can_save = max(max_points_can_save, points_saved + points_saved_second)
	return max_points_can_save

def _find_max_range(points_xs, range_size):
	if not points_xs:
		return ((0, range_size), 0)
	points_xs = sorted(points_xs)
	points_n = len(points_xs)
	first_x = points_xs[0]
	last_x = first_x + range_size
	max_range = None
	max_range_value = 0
	i_points_begin = 0
	i_points_end = 0
	while True:
		while i_points_begin < points_n and points_xs[i_points_begin] < first_x:
			i_points_begin += 1
		while i_points_end < points_n and points_xs[i_points_end] <= last_x:
			i_points_end += 1
		if i_points_end - i_points_begin > max_range_value:
			max_range = (first_x, last_x)
			max_range_value = i_points_end - i_points_begin
		if i_points_end >= points_n:
			break
		last_x = points_xs[i_points_end]
		first_x = last_x - range_size
	return (max_range, max_range_value)

def _compute_ranges(points_xs, range_size):
	if not points_xs:
		return ((0, range_size), 0)
	points_xs = sorted(points_xs)
	points_n = len(points_xs)
	computed_ranges = []
	first_x = points_xs[0]
	last_x = first_x + range_size
	i_points_begin = 0
	i_points_end = 0
	while True:
		while i_points_begin < points_n and points_xs[i_points_begin] < first_x:
			i_points_begin += 1
		while i_points_end < points_n and points_xs[i_points_end] <= last_x:
			i_points_end += 1
		computed_ranges.append(((first_x, last_x), i_points_end - i_points_begin))
		if i_points_end >= points_n:
			break
		last_x = points_xs[i_points_end]
		first_x = last_x - range_size
	return computed_ranges
main()


import sys
import math
mod = 998244353
cases = True
dynamic_factorial = False

def main(test_case=False):
	n = int(input()) if test_case else 1
	for _ in range(n):
		test()

def fast_pow(a: int, b: int):
	res = 1
	while b > 0:
		if b & 1:
			res *= a
		a *= a
		b >>= 1
	return res

def c2(n):
	return n * (n - 1) // 2

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

def bits(n: int):
	return list(bin(n)).count('1')

def flush():
	sys.stdout.flush()

def parr(arr):
	print(*arr, sep=' ')

def gcd(a, b):
	while b:
		if b % a == 0:
			break
		tmp = a
		a = b % a
		b = tmp
	return a

def ext_gcd(a: int, b: int):
	if b == 0:
		return [a, [1, 0]]
	res = ext_gcd(b, a % b)
	g = res[0]
	if g != 1:
		return False
	x1 = res[1][0]
	y1 = res[1][1]
	x = y1
	y = x1 - y1 * (a // b)
	return [g, [x, y]]

def get_set(a):
	res = {}
	for x in a:
		if x in res:
			res[x] += 1
		else:
			res[x] = 1
	return res
fact = {0: 1}

def factorial(n):
	if dynamic_factorial:
		if n not in fact:
			fact[n] = factorial(n - 1) * n
		return fact[n]
	else:
		res = 1
		while n > 0:
			res = res * n % mod
			n -= 1
		return res

def sum_of(a):
	res = 0
	for x in a:
		res = (res + x) % mod
	return res

def prod_of(a):
	res = 1
	for x in a:
		res = res * x % mod
	return res

def test():
	(n, k) = get()
	x = get()
	input()
	x.sort()
	left = [0] * n
	right = [0] * n
	(i, j) = (0, 0)
	while i < n:
		while x[i] - x[j] > k:
			j += 1
		left[i] = i - j + 1
		if i > 0:
			left[i] = max(left[i], left[i - 1])
		i += 1
	(i, j) = (n - 1, n - 1)
	while i >= 0:
		while x[j] - x[i] > k:
			j -= 1
		right[i] = j - i + 1
		if i < n - 1:
			right[i] = max(right[i], right[i + 1])
		i -= 1
	i = 1
	ans = 1
	while i < n:
		ans = max(ans, right[i] + left[i - 1])
		i += 1
	print(ans)
main(cases)


for t in range(int(input())):
	(n, k) = map(int, input().split())
	lx = list(map(int, input().split()))
	ly = list(map(int, input().split()))
	lx = list(sorted(lx))
	ll = [0]
	pi = 0
	for i in range(len(lx)):
		while lx[i] > lx[pi] + k:
			pi += 1
		ll.append(i - pi + 1)
	lr = [0]
	pi = n - 1
	for i in range(len(lx) - 1, -1, -1):
		while lx[pi] > lx[i] + k:
			pi -= 1
		lr.append(pi - i + 1)
	for i in range(1, len(ll)):
		ll[i] = max(ll[i], ll[i - 1])
	for i in range(1, len(lr)):
		lr[i] = max(lr[i], lr[i - 1])
	lr = lr[::-1]
	ans = 0
	for i in range(len(ll)):
		ans = max(ans, ll[i] + lr[i])
	print(ans)


from sys import stdin
input = stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = sorted(list(map(int, input().split())))
	y = list(map(int, input().split()))
	mostSaved = [0] * (n + 1)
	savedFromStart = [0] * n
	(i, j) = (0, 0)
	prevX = -1
	while i < n:
		if x[i] == prevX:
			savedFromStart[i] = savedFromStart[i - 1]
		else:
			prevX = x[i]
			while j < n and x[j] <= x[i] + k:
				j += 1
			savedFromStart[i] = j - i
		i += 1
	for i in range(n - 1, -1, -1):
		mostSaved[i] = max(mostSaved[i + 1], savedFromStart[i])
	out = [savedFromStart[i] + mostSaved[min(n, i + savedFromStart[i])] for i in range(n)]
	print(max(out))


import bisect

def solve(n, x_coords, y_coords, k, ans):
	x_coords.sort()
	dp = []
	for i in range(n):
		x = x_coords[i]
		index = bisect.bisect(x_coords, x + k) - 1
		dp.append(index - i + 1)
	dp_max = []
	for i in reversed(dp):
		if not dp_max:
			dp_max.append(i)
		else:
			dp_max.append(max(dp_max[-1], i))
	dp_max.reverse()
	max_val = 0
	for i in range(n):
		x = x_coords[i]
		index = bisect.bisect(x_coords, x + k) - 1
		val = index - i + 1
		if index + 1 < n:
			val += dp_max[index + 1]
		max_val = max(max_val, val)
	ans.append(str(max_val))

def main():
	t = int(input())
	ans = []
	for i in range(t):
		(n, k) = list(map(int, input().split()))
		x_coords = list(map(int, input().split()))
		y_coords = list(map(int, input().split()))
		solve(n, x_coords, y_coords, k, ans)
	print('\n'.join(ans))
main()


from bisect import bisect, bisect_left
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = input()
	x.sort()
	a = []
	b = []
	i = 0
	while i < n:
		b.append(bisect(x, x[i] + k) - i)
		a.append(i - bisect_left(x, x[i] - k) + 1)
		i += 1
	b.reverse()
	for i in range(1, n):
		a[i] = max(a[i], a[i - 1])
		b[i] = max(b[i], b[i - 1])
	b.reverse()
	m = 1
	for i in range(n - 1):
		m = max(a[i] + b[i + 1], m)
	print(m)


import sys
input = sys.stdin.readline
t = int(input())
for tests in range(t):
	(n, k) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	X2 = sorted(X)
	S = [0] * n
	LAST = [0] * n
	end = 0
	for start in range(n):
		v = X2[start]
		while end < n and X2[end] <= v + k:
			end += 1
		S[start] = end - start
		LAST[start] = end
	if max(S) == n:
		print(n)
		continue
	MAXS = [0] * n
	MAXS[-1] = S[-1]
	for i in range(n - 2, -1, -1):
		MAXS[i] = max(S[i], MAXS[i + 1])
	ANS = 0
	for i in range(n):
		if LAST[i] == n:
			break
		ANS = max(ANS, S[i] + MAXS[LAST[i]])
	print(ANS)


t = int(input().strip())
for _ in range(t):
	(n, k) = map(int, input().split())
	arr = [int(i) for i in input().split()]
	xx = input()
	if n == 1:
		print(1)
	else:
		arr.sort()
		cnt = [0 for i in range(n)]
		left = arr[0]
		right = left + k
		for i in range(n):
			if arr[i] <= right:
				cnt[0] += 1
			else:
				break
		index = 1
		right_point = i
		cons = 1
		while index < n:
			left = arr[index]
			if arr[index] != arr[index - 1]:
				cnt[index] = cnt[index - 1] - cons
				cons = 1
				for i in range(right_point, n):
					if arr[i] > left + k:
						right_point = i
						break
					if i == n - 1:
						right_point = n
					cnt[index] += 1
			else:
				cons += 1
				cnt[index] = cnt[index - 1]
			index += 1
		dp = [0 for i in range(n + 1)]
		for i in range(n - 1, -1, -1):
			dp[i] = max(dp[i + 1], cnt[i])
		ans = 0
		for i in range(n):
			result = cnt[i] + (0 if i + cnt[i] >= n else dp[i + cnt[i]])
			if result > ans:
				ans = result
		print(ans)


import os, sys
from io import BytesIO, IOBase
from collections import Counter, deque

def main():
	for _ in range(int(input())):
		(n, k) = map(int, input().split())
		x = list(map(int, input().split()))
		y = list(map(int, input().split()))
		cou = Counter(x)
		poi = sorted(set(x))
		dct = {}
		points = deque([cou[poi[0]]])
		ind = deque([poi[0]])
		su = cou[poi[0]]
		dct[poi[0], poi[0] - k] = su
		for i in range(1, len(poi)):
			while len(ind) and poi[i] - ind[0] > k:
				ind.popleft()
				su -= points.popleft()
			points.append(cou[poi[i]])
			ind.append(poi[i])
			su += cou[poi[i]]
			dct[poi[i], poi[i] - k] = su
		while len(ind):
			yy = ind.popleft()
			dct[yy + k, yy] = su
			su -= points.popleft()
		r = sorted(dct.keys(), key=dct.get, reverse=True)
		xxx = sorted(r, key=lambda zzz: zzz[0])
		if len(set(x)) == 1:
			print(n)
			continue
		ans = 0
		i = 0
		for j in xxx:
			while i != len(r) and (not r[i][1] > j[0]):
				i += 1
			if i <= len(r) - 1:
				ans = max(ans, dct[j] + dct[r[i]])
		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()


from bisect import *
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = sorted(map(int, input().split()))
	y = input()
	(forward, backward, maxBack) = ([], [0], 0)
	ans = 0
	for i in range(n):
		rgt = bisect_right(x, x[i] + k)
		lft = bisect_left(x, x[i] - k)
		forward.append(rgt - i)
		backward.append(i - lft + 1)
		ans = max(ans, rgt - i + maxBack)
		maxBack = max(maxBack, backward[-1])
	print(ans)


from bisect import bisect_left, bisect_right

def count(x, y, List):
	return bisect_right(List, y) - bisect_right(List, x - 1)

def solve():
	(N, K) = map(int, input().split())
	X = list(map(int, input().split()))
	Y = list(map(int, input().split()))
	X.sort()
	saver_count = [0 for i in range(N)]
	for i in range(N - 1, -1, -1):
		left = X[i]
		saver_count[i] = count(left, left + K, X)
		if i < N - 1:
			saver_count[i] = max(saver_count[i], saver_count[i + 1])
	res = 0
	for i in range(N):
		sub_max = 0
		left = X[i]
		sub_max += count(left, left + K, X)
		right_count = bisect_right(X, left + K)
		if right_count == N:
			res = max(res, sub_max)
			continue
		else:
			res = max(res, sub_max + saver_count[right_count])
	print(res)
	return

def main():
	T = int(input())
	for i in range(T):
		solve()
	return
main()


def run():
	(n, k) = map(int, input().split())
	xS = list(map(int, input().split()))
	yS = list(map(int, input().split()))
	(lMax, rMax) = ([0] * n, [0] * n)
	xS.sort()
	j = n - 1
	for i in range(n - 1, -1, -1):
		while xS[j] - xS[i] > k:
			j -= 1
		rMax[i] = j - i + 1
		if i + 1 < n:
			rMax[i] = max(rMax[i], rMax[i + 1])
	j = 0
	for i in range(n):
		while xS[i] - xS[j] > k:
			j += 1
		lMax[i] = i - j + 1
		if i > 0:
			lMax[i] = max(lMax[i], lMax[i - 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, rMax[i + 1] + lMax[i])
	print(ans)
if 1:
	for i in range(int(input())):
		run()
else:
	run()


import sys, math
input = sys.stdin.readline
t = int(input())
for r in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	prefix = [0] * n
	suffix = [0] * n
	i = 0
	j = 1
	prefix[i] = 1
	current = x[0]
	while j < n:
		if x[j] - current <= k:
			prefix[j] = max(prefix[j - 1], j - i + 1)
			j += 1
		else:
			i += 1
			current = x[i]
	x = x[::-1]
	i = 0
	j = 1
	suffix[i] = 1
	current = x[0]
	while j < n:
		if current - x[j] <= k:
			suffix[j] = max(suffix[j - 1], j - i + 1)
			j += 1
		else:
			i += 1
			current = x[i]
	suffix = suffix[::-1]
	ans = max(prefix[n - 1], suffix[0])
	for i in range(n - 1):
		ans = max(ans, prefix[i] + suffix[i + 1])
	print(ans)


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

def main():
	import sys
	from bisect import bisect_left
	input = sys.stdin.buffer.readline

	def STfunc(a, b):
		if a > b:
			return a
		else:
			return b

	class SparseTable:

		def __init__(self, A):
			self.N = len(A)
			self.K = self.N.bit_length() - 1
			self.table = [0] * (self.N * (self.K + 1))
			for (i, a) in enumerate(A):
				self.table[i] = a
			for k in range(1, self.K + 1):
				for i in range(self.N):
					j = i + (1 << k - 1)
					if j <= self.N - 1:
						self.table[i + k * self.N] = STfunc(self.table[i + (k - 1) * self.N], self.table[j + (k - 1) * self.N])

		def query(self, l, r):
			k = (r - l).bit_length() - 1
			return STfunc(self.table[l + k * self.N], self.table[r - (1 << k) + k * self.N])
	for t in range(int(input())):
		(N, K) = map(int, input().split())
		X = list(map(int, input().split()))
		Y = list(map(int, input().split()))
		X.sort()
		r = 0
		num = [0] * N
		R = [0] * N
		for l in range(N):
			if r < N:
				while X[l] + K >= X[r]:
					r += 1
					if r == N:
						break
			num[l] = r - l
			R[l] = r
		ST = SparseTable(num)
		ans = 0
		for l in range(N - 1, -1, -1):
			r = R[l]
			ans = max(ans, num[l] + num[r - 1] - 1)
			if r < N:
				ans = max(ans, num[l] + ST.query(r, N))
		print(ans)
main()


from __future__ import division, print_function
from fractions import Fraction
import sys
import os
from io import BytesIO, IOBase
from itertools import *
import bisect
from heapq import *
from math import ceil, floor
from copy import *
from collections import deque, defaultdict
from collections import Counter as counter
from itertools import combinations
from itertools import permutations as permutate
from bisect import bisect_left as bl
from operator import *
from bisect import bisect_right as br
from bisect import bisect
BUFSIZE = 8192
from sys import stderr

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

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))
mod = 1000000007

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 fsep():
	return map(float, inp().split())

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

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

def pow(x, y, p):
	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
from functools import reduce

def factors(n):
	return set(reduce(list.__add__, ([i, n // i] for i in range(1, int(n ** 0.5) + 1) if n % i == 0)))

def gcd(a, b):
	if a == b:
		return a
	while b > 0:
		(a, b) = (b, a % b)
	return a

def prefix_sum(ar):
	return list(accumulate(ar))

def suffix_sum(ar):
	return list(accumulate(ar[::-1]))[::-1]

def N():
	return int(inp())
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]

def YES():
	print('YES')

def NO():
	print('NO')

def Yes():
	print('Yes')

def No():
	print('No')
from collections import defaultdict

def numberOfSetBits(i):
	i = i - (i >> 1 & 1431655765)
	i = (i & 858993459) + (i >> 2 & 858993459)
	return ((i + (i >> 4) & 252645135) * 16843009 & 4294967295) >> 24

class MergeFind:

	def __init__(self, n):
		self.parent = list(range(n))
		self.size = [1] * n
		self.num_sets = n

	def find(self, a):
		to_update = []
		while a != self.parent[a]:
			to_update.append(a)
			a = self.parent[a]
		for b in to_update:
			self.parent[b] = a
		return self.parent[a]

	def merge(self, a, b):
		a = self.find(a)
		b = self.find(b)
		if a == b:
			return
		self.num_sets -= 1
		self.parent[a] = b
		self.size[b] += self.size[a]

	def set_size(self, a):
		return self.size[self.find(a)]

	def __len__(self):
		return self.num_sets

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

def solve():
	(n, k) = sep()
	x = lis()
	x.sort()
	inp()
	ar = [0] * n
	for i in range(n):
		s = x[i]
		e = s + k
		t = br(x, e)
		ar[i] = t - i
	m = 0
	mas = [0] * n
	mas[n - 1] = ar[n - 1]
	for i in range(n - 2, -1, -1):
		mas[i] = max(ar[i], mas[i + 1])
	mas.append(0)
	for i in range(n):
		s = x[i]
		e = s + k
		t = br(x, e)
		m = max(m, ar[i] + mas[t])
	print(m)
testcase(int(inp()))


from bisect import bisect_right as br
from bisect import bisect_left as bl
t = int(input())
for i in range(t):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	ans = 0
	cnt = [0] * (2 * n)
	for i in range(n - 1, -1, -1):
		left = x[i]
		right = x[i] + k
		curL = bl(x, left)
		curR = br(x, right)
		curcnt = curR - curL
		cnt[i] = max(cnt[i + 1], curcnt)
		ans = max(ans, curcnt + cnt[curR])
	print(ans)


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from math import inf, floor, log

def main():

	def solve():

		def createSparseTable():
			sparseTable = [[i] for i in range(n)]
			for j in range(1, floor(log(n, 2)) + 1):
				for i in range(n):
					length = 1 << j
					if i + length - 1 > n - 1:
						break
					sparseTable[i].append(0)
					indexOfMax1 = sparseTable[i][j - 1]
					indexOfMax2 = sparseTable[i + length // 2][j - 1]
					if savedByBar[indexOfMax1] > savedByBar[indexOfMax2]:
						sparseTable[i][j] = indexOfMax1
					else:
						sparseTable[i][j] = indexOfMax2
			return sparseTable

		def getMaxSavedStartingAt(start):
			rangeLength = n - start
			checkLength = floor(log(rangeLength, 2))
			indexOfMax1 = sparseTable[start][checkLength]
			numbersLeft = rangeLength - (1 << checkLength)
			indexOfMax2 = sparseTable[start + numbersLeft][checkLength]
			return max(savedByBar[indexOfMax1], savedByBar[indexOfMax2])

		def find(low, xBoundary, mode):
			high = n - 1
			while low < high:
				mid = (high + low) // 2
				if x[mid] > xBoundary:
					high = mid - 1
				else:
					low = mid + 1
			mid = (high + low) // 2
			if mode == 1:
				return mid if x[mid] <= xBoundary else max(mid - 1, 0)
			else:
				return mid if x[mid] > xBoundary else mid + 1
		(n, k) = [int(x) for x in input().split()]
		x = [int(x) for x in input().split()]
		x.sort()
		input()
		savedByBar = [-inf] * n
		for leftmost in range(n):
			rightmost = find(leftmost, x[leftmost] + k, 1)
			savedByBar[leftmost] = max(rightmost - leftmost + 1, savedByBar[leftmost])
		sparseTable = createSparseTable()
		maxSaved = 1
		for leftBar in range(n - 1):
			firstNotOverlapping = find(leftBar, x[leftBar] + k, 2)
			if firstNotOverlapping > n - 1:
				maxSaved = max(getMaxSavedStartingAt(leftBar), maxSaved)
				break
			savedByRightBar = getMaxSavedStartingAt(firstNotOverlapping)
			maxSaved = max(savedByBar[leftBar] + savedByRightBar, maxSaved)
			if maxSaved == n:
				break
		print(maxSaved)
	t = int(input())
	for i in range(t):
		solve()
BUFFSIZE = 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, BUFFSIZE))
			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, BUFFSIZE))
			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')
input = lambda : sys.stdin.readline().rstrip('\r\n')

def print(*args, **kwargs):
	sep = kwargs.pop('sep', ' ')
	file = kwargs.pop('file', sys.stdout)
	atStart = True
	for x in args:
		if not atStart:
			file.write(sep)
		file.write(str(x))
		atStart = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
main()


import bisect
t = int(input())
for you in range(t):
	l = input().split()
	n = int(l[0])
	k = int(l[1])
	l = input().split()
	li = [int(i) for i in l]
	l = input()
	li.sort()
	dp = [[0 for i in range(2)] for i in range(n)]
	maxas = [0 for i in range(n)]
	dp[-1][0] = 1
	dp[-1][1] = 1
	maxas[-1] = 1
	for i in range(n - 2, -1, -1):
		if li[i] + k >= li[-1]:
			dp[i][0] = n - i
			dp[i][1] = n - i
			maxas[i] = max(maxas[i + 1], dp[i][0])
			continue
		z = bisect.bisect_right(li, li[i] + k)
		dp[i][0] = z - i
		maxas[i] = max(maxas[i + 1], dp[i][0])
		dp[i][1] = z - i + maxas[z]
	maxa = 0
	for i in range(n):
		maxa = max(maxa, dp[i][0])
		maxa = max(maxa, dp[i][1])
	print(maxa)


import sys
ii = lambda : sys.stdin.readline().strip()
idata = lambda : [int(x) for x in ii().split()]

def solve():
	(n, k) = idata()
	x = sorted(idata())
	y = idata()
	(l, r) = ([0] * n, [0] * n)
	j = n - 1
	for i in range(n - 1, -1, -1):
		while x[j] - x[i] > k:
			j -= 1
		r[i] = j - i + 1
		if i + 1 < n:
			r[i] = max(r[i], r[i + 1])
	j = 0
	for i in range(n):
		while x[i] - x[j] > k:
			j += 1
		l[i] = i - j + 1
		if i > 0:
			l[i] = max(l[i], l[i - 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, l[i] + r[i + 1])
	print(ans)
	return
for t in range(int(ii())):
	solve()


import bisect
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = input()
	x.sort()
	X = [bisect.bisect_right(x, x[i] + k) for i in range(n)]
	Y = [0]
	for i in range(n - 1, -1, -1):
		Y += [max(Y[-1], X[i] - i)]
	Y.reverse()
	ans = 0
	for i in range(n):
		ans = max(ans, X[i] - i + Y[X[i]])
	print(ans)


from bisect import *
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	(x, y) = (sorted(map(int, input().split())), input())
	left = [[0, 0, 0] for i in range(n)]
	for i in range(n):
		idx = bisect_left(x, x[i] - k)
		left[i][0] = i - idx + 1
		left[i][1] = max(left[i - 1][0], left[i - 1][1]) if i > 0 else 0
		left[i][2] = max(left[i - 1][2], left[i][0] + left[idx][1]) if idx else max(left[i][0], left[i][1])
	print(left[-1][-1])


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = sorted(map(int, input().split()))
	input()
	right = [0] * n
	curr = n - 1
	for i in range(n - 1, -1, -1):
		while x[curr] > x[i] + k:
			curr -= 1
		right[i] = curr
	maxsave = [0] * n
	curr = 0
	for i in range(n - 1, -1, -1):
		maxsave[i] = curr
		curr = max(right[i] - i + 1, curr)
	out = [right[i] - i + 1 + maxsave[right[i]] for i in range(n)]
	print(max(out))


import collections

def solve(x_coords, k):
	x_coords.sort()
	left = 0
	right = 0
	answers = collections.deque()
	while right < len(x_coords) and x_coords[right] - x_coords[0] <= k:
		right += 1
		answers.append((right - 1, right))
	mx_before = 0
	ans = right
	while right < len(x_coords):
		while x_coords[right] - x_coords[left] > k:
			left += 1
		while answers and x_coords[right] - x_coords[answers[0][0]] > k:
			mx_before = max(mx_before, answers.popleft()[1])
		right += 1
		cur = right - left
		ans = max(ans, cur + mx_before)
		answers.append((right - 1, cur))
	return ans
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	(*x_coords,) = map(int, input().split())
	_ = input()
	print(solve(x_coords, k))


import sys
import math
import collections
import bisect
import itertools
import decimal
import copy
INF = 10 ** 20
ni = lambda : int(sys.stdin.readline().rstrip())
ns = lambda : map(int, sys.stdin.readline().rstrip().split())
na = lambda : list(map(int, sys.stdin.readline().rstrip().split()))
na1 = lambda : list(map(lambda x: int(x) - 1, sys.stdin.readline().rstrip().split()))

def main():
	t = ni()
	for _ in range(t):
		(n, k) = ns()
		x = na()
		y = na()
		x.sort()
		x_point = []
		for i in range(n):
			idx = bisect.bisect_right(x, x[i] + k)
			x_point.append(idx - i)
		m = 0
		second = [0 for _ in range(n + 1)]
		for i in range(n - 1, -1, -1):
			m = max(m, x_point[i])
			second[i] = m
		ans = 0
		for i in range(n):
			tans = x_point[i] + second[i + x_point[i]]
			ans = max(ans, tans)
		print(ans)
main()


from sys import stdin, stdout

def two_platforms(n, k, x_a):
	x_a.sort()
	la = [0] * n
	ra = [0] * n
	hi = 0
	mx = 0
	for i in range(n):
		while hi < i and x_a[i] - x_a[hi] > k:
			hi += 1
		mx = max(mx, i - hi + 1)
		la[i] = mx
	tj = n - 1
	mx = 0
	for j in range(n - 1, -1, -1):
		while tj > j and x_a[tj] - x_a[j] > k:
			tj -= 1
		mx = max(mx, tj - j + 1)
		ra[j] = mx
	ans = ra[0]
	for i in range(0, n - 1):
		ans = max(ans, la[i] + ra[i + 1])
	return ans
t = int(stdin.readline())
for num in range(t):
	(n, k) = map(int, stdin.readline().split())
	x_a = list(map(int, stdin.readline().split()))
	y_a = list(map(int, stdin.readline().split()))
	ans = two_platforms(n, k, x_a)
	stdout.write(str(ans) + '\n')


import sys
input = sys.stdin.readline
t = int(input())
for _ in range(t):
	(n, k) = list(map(int, input().split()))
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	take = n - 1
	suffix = [0] * n
	for i in range(n - 1, -1, -1):
		while x[i] + k < x[take]:
			take -= 1
		suffix[i] = take - i + 1
	mx = 0
	for i in range(n - 1, -1, -1):
		mx = max(suffix[i], mx)
		suffix[i] = mx
	ans = 1
	take = 0
	for i in range(n - 1):
		while x[i] - k > x[take]:
			take += 1
		temp = i - take + 1
		ans = max(ans, temp + suffix[i + 1])
	print(ans)


from bisect import *
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	x.sort()
	pref = []
	suff = []
	for i in range(n):
		j = bisect_right(x, x[i] + k)
		pref.append(j - i)
		l = bisect_left(x, x[i] - k) - 1
		suff.append(i - l)
	for i in range(n - 2, -1, -1):
		pref[i] = max(pref[i], pref[i + 1])
	for i in range(1, n):
		suff[i] = max(suff[i], suff[i - 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, suff[i] + pref[i + 1])
	print(ans)


import sys
LI = lambda : list(map(int, sys.stdin.readline().strip('\n').split()))
MI = lambda : map(int, sys.stdin.readline().strip('\n').split())
SI = lambda : sys.stdin.readline().strip('\n')
II = lambda : int(sys.stdin.readline().strip('\n'))
for _ in range(II()):
	(n, k) = MI()
	a = sorted(MI())
	b = MI()
	(l, r) = ([0] * n, [0] * n)
	for i in range(n):
		(s, e) = (0, i - 1)
		ret = -1
		val = a[i] - k
		while s <= e:
			m = (s + e) // 2
			if a[m] >= val:
				e = m - 1
			else:
				s = m + 1
				ret = m
		l[i] = i - ret if ret != -1 else i + 1
		(s, e) = (i + 1, n - 1)
		ret = -1
		val = a[i] + k
		while s <= e:
			m = (s + e) // 2
			if a[m] <= val:
				s = m + 1
			else:
				e = m - 1
				ret = m
		r[i] = ret - i if ret != -1 else n - i
	for i in range(1, n):
		l[i] = max(l[i], l[i - 1])
	for i in range(n - 2, -1, -1):
		r[i] = max(r[i], r[i + 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, l[i] + r[i + 1])
	print(ans)


from sys import stdin
import math
from bisect import *
g = lambda : stdin.readline().strip()
gl = lambda : g().split()
gil = lambda : [int(var) for var in gl()]
gfl = lambda : [float(var) for var in gl()]
gcl = lambda : list(g())
gbs = lambda : [int(var) for var in g()]
mod = int(1000000000.0) + 7
inf = float('inf')
(t,) = gil()
for _ in range(t):
	(n, k) = gil()
	p = gil()
	p.sort()
	g()
	if p[-1] - p[0] <= 2 * k:
		print(n)
	else:
		lens = []
		for i in range(n):
			j = bisect_right(p, p[i] + k) - 1
			lens.append(j - i + 1)
		maxLens = lens.copy()
		for i in reversed(range(n - 1)):
			maxLens[i] = max(maxLens[i], maxLens[i + 1])
		ans = 0
		for i in range(n):
			nex = maxLens[lens[i] + i] if lens[i] + i < n else 0
			ans = max(ans, lens[i] + nex)
		print(ans)


from bisect import bisect_right
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	x = sorted(map(int, input().split()))
	(*y,) = map(int, input().split())
	cnt = 0
	cntlst = [0] * (n + 1)
	for i in range(n - 1, -1, -1):
		left = i
		right = bisect_right(x, x[i] + k)
		if cnt < right - left:
			cnt = right - left
		cntlst[i] = cnt
	ans = 0
	for i in range(n):
		left = i
		right = bisect_right(x, x[i] + k)
		ans = max(ans, right - left + cntlst[right])
	print(ans)


from bisect import bisect_left as lower_bound, bisect_right as upper_bound
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	x = sorted(map(int, input().split()))
	input()
	mxr = [0] * n
	for i in range(n - 1, -1, -1):
		mxr[i] = i - lower_bound(x, x[i] - k) + 1
	ans = 1
	cmxr = mxr[0]
	for i in range(1, n):
		res = cmxr
		cmxr = max(cmxr, mxr[i])
		cf = upper_bound(x, x[i] + k) - i
		ans = max(ans, res + cf)
	print(ans)


from bisect import bisect_left as bl

def solve(n, k, a):
	b = [0] * n
	for i in range(n):
		b[i] = i - bl(a, a[i] - k) + 1
	pr = [b[0]]
	for i in range(1, n):
		pr.append(max(pr[-1], b[i]))
	res = 0
	for y in range(n):
		res = max(res, b[y])
		if y - b[y] >= 0:
			res = max(res, pr[y - b[y]] + b[y])
	return res

def main():
	t = int(input())
	for tt in range(t):
		(n, k) = [int(i) for i in input().split()]
		x = [int(i) for i in input().split()]
		_ = input()
		print(solve(n, k, sorted(x)))
main()


import sys
t = int(input())
for _ in range(t):
	[n, k] = map(int, input().split())
	x = list(map(int, input().split()))
	x.sort()
	input()
	j = n - 1
	r = [0] * n
	for i in range(n - 1, -1, -1):
		while x[j] - x[i] > k:
			j -= 1
		r[i] = j - i + 1
	j = 0
	l = [0] * n
	for i in range(0, n):
		while x[i] - x[j] > k:
			j += 1
		l[i] = i - j + 1
	for i in range(1, n):
		l[i] = max(l[i - 1], l[i])
	for i in range(n - 2, -1, -1):
		r[i] = max(r[i + 1], r[i])
	ans = 1
	for i in range(0, n - 1):
		ans = max(l[i] + r[i + 1], ans)
	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.readline())

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

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

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

def SI():
	return sys.stdin.readline()[:-1]
from collections import defaultdict, deque
for _ in range(II()):
	(_, k) = MI()
	xx = LI()
	yy = LI()
	xtoc = defaultdict(int)
	for x in xx:
		xtoc[x] += 1
	xx = []
	cc = []
	for (x, c) in sorted(xtoc.items()):
		xx.append(x)
		cc.append(c)
	n = len(cc)
	s = 0
	j = 0
	mx = 0
	ll = []
	for (i, (c, x)) in enumerate(zip(cc, xx)):
		s += c
		while j < n and x - xx[j] > k:
			s -= cc[j]
			j += 1
		mx = max(mx, s)
		ll.append(mx)
	s = 0
	j = n - 1
	mx = 0
	rr = []
	for i in range(n - 1, -1, -1):
		s += cc[i]
		while j >= 0 and -xx[i] + xx[j] > k:
			s -= cc[j]
			j -= 1
		mx = max(mx, s)
		rr.append(mx)
	rr = rr[::-1]
	ans = 0
	for i in range(n - 1):
		ans = max(ans, ll[i] + rr[i + 1])
	if n == 1:
		ans = cc[0]
	print(ans)


from sys import stdin, stdout
input = stdin.buffer.readline
for _ in range(int(input())):
	(n, k) = map(int, input().split())
	(*x,) = map(int, input().split())
	(*y,) = map(int, input().split())
	a = [[x[i], y[i]] for i in range(n)]
	b = [0] * n
	c = [0] * (n + 1)
	dp = [0] * (n + 1)
	a.sort()
	j = 0
	c[0] = a[0][0]
	b[0] = 1
	for i in range(1, n):
		if a[i][0] != a[i - 1][0]:
			j += 1
			c[j] = a[i][0]
		b[j] += 1
	pref = [0] * (n + 1)
	for i in range(n):
		pref[i] = pref[i - 1] + b[i]
	i = j = 0
	ans = 0
	while i < n:
		while c[i] - c[j] > k:
			j += 1
		ans = max(ans, dp[j - 1] + pref[i] - pref[j - 1])
		dp[i] = max(dp[i - 1], pref[i] - pref[j - 1])
		i += 1
	print(ans)


t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	xs = list(map(int, input().split()))
	ys = list(map(int, input().split()))
	pts = list(zip(xs, ys))
	pts.sort(key=lambda p: p[0])
	dp = []
	rp = 0
	for i in range(n):
		while rp < n and pts[rp][0] - pts[i][0] <= k:
			rp += 1
		dp.append(rp - i)
	suffixes = [0] * n
	suffixes[-1] = dp[-1]
	for i in range(n - 2, -1, -1):
		suffixes[i] = max(suffixes[i + 1], dp[i])
	suffixes.append(0)
	ans = 0
	rp = 0
	for i in range(n):
		while rp < n and pts[rp][0] - pts[i][0] <= k:
			rp += 1
		ans = max(ans, dp[i] + suffixes[rp])
	print(ans)


from bisect import bisect_left, bisect_right
t = int(input())
for _ in range(t):
	(n, k) = map(int, input().split())
	xl = list(map(int, input().split()))
	yl = list(map(int, input().split()))
	xl.sort()
	left_cnts = []
	for (i, x) in enumerate(xl):
		rx = x + k
		ind_r = bisect_right(xl, rx) - 1
		cnt = ind_r - i + 1
		left_cnts.append((cnt, ind_r))
	right_max_cnts = [-1] * n
	cmax = 0
	for i in range(n - 1, -1, -1):
		x = xl[i]
		rx = x + k
		ind_r = bisect_right(xl, rx) - 1
		cnt = ind_r - i + 1
		cmax = max(cmax, cnt)
		right_max_cnts[i] = cmax
	ans = 0
	for (cnt, ind_r) in left_cnts:
		if ind_r == n - 1:
			ans = max(ans, cnt)
		else:
			v = cnt + right_max_cnts[ind_r + 1]
			ans = max(ans, v)
	print(ans)


import time, math as mt, bisect, sys
from sys import stdin, stdout
from collections import deque
from fractions import Fraction
from collections import Counter
from collections import OrderedDict
pi = 3.141592653589793

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

def IO():
	return stdin.readline()

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

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

def P(x):
	return stdout.write(str(x) + '\n')

def PI(x, y):
	return stdout.write(str(x) + ' ' + str(y) + '\n')

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

def gcd(a, b):
	if a == 0:
		return b
	elif b == 0:
		return a
	if a > b:
		return gcd(a % b, b)
	else:
		return gcd(a, b % a)

def bfs(adj, v):
	visited = [False] * (v + 1)
	q = deque()
	while q:
		pass

def sieve():
	li = [True] * 1000001
	(li[0], li[1]) = (False, False)
	for i in range(2, len(li), 1):
		if li[i] == True:
			for j in range(i * i, len(li), i):
				li[j] = False
	prime = []
	for i in range(1000001):
		if li[i] == True:
			prime.append(i)
	return prime

def setBit(n):
	count = 0
	while n != 0:
		n = n & n - 1
		count += 1
	return count
mx = 10 ** 7
spf = [mx] * (mx + 1)

def SPF():
	spf[1] = 1
	for i in range(2, mx + 1):
		if spf[i] == mx:
			spf[i] = i
			for j in range(i * i, mx + 1, i):
				if i < spf[j]:
					spf[j] = i
	return

def readTree(v):
	adj = [set() for i in range(v + 1)]
	for i in range(v - 1):
		(u1, u2) = In()
		adj[u1].add(u2)
		adj[u2].add(u1)
	return adj
mod = 10 ** 9 + 7

def solve():
	(n, k) = IP()
	x = L()
	y = L()
	x.sort()
	(l, r) = ([0] * n, [0] * n)
	j = n - 1
	for i in range(n - 1, -1, -1):
		while x[j] - x[i] > k:
			j -= 1
		r[i] = j - i + 1
		if i + 1 < n:
			r[i] = max(r[i], r[i + 1])
	j = 0
	for i in range(n):
		while x[i] - x[j] > k:
			j += 1
		l[i] = i - j + 1
		if i - 1 >= 0:
			l[i] = max(l[i], l[i - 1])
	ans = 1
	for i in range(n - 1):
		ans = max(ans, l[i] + r[i + 1])
	print(ans)
	return
t = II()
for i in range(t):
	solve()


from collections import defaultdict
from bisect import bisect_right, bisect_left

def main():
	for _ in range(int(input())):
		(n, k) = list(map(int, input().split()))
		x = list(map(int, input().split()))
		y = list(map(int, input().split()))
		x.sort()
		d = defaultdict(lambda : 0)
		(x1, m1) = (0, 0)
		a = x
		ans = [0] * n
		for i in range(n):
			ans[i] = bisect_right(x, x[i] + k) - i
		maxi = [0] * n
		maxi[-1] = ans[-1]
		for i in range(n - 2, -1, -1):
			maxi[i] = max(ans[i], maxi[i + 1])
		fa = 0
		for i in range(n):
			if ans[i] + i < n:
				fa = max(fa, ans[i] + maxi[i + ans[i]])
		print(max(fa, max(maxi)))
main()


from math import inf, log2

class SegmentTree:

	def __init__(self, array, func=max):
		self.n = len(array)
		self.size = 2 ** (int(log2(self.n - 1)) + 1) if self.n != 1 else 1
		self.func = func
		self.default = 0 if self.func != min else inf
		self.data = [self.default] * (2 * self.size)
		self.process(array)

	def process(self, array):
		self.data[self.size:self.size + self.n] = array
		for i in range(self.size - 1, -1, -1):
			self.data[i] = self.func(self.data[2 * i], self.data[2 * i + 1])

	def query(self, alpha, omega):
		if alpha == omega:
			return self.data[alpha + self.size]
		res = self.default
		alpha += self.size
		omega += self.size + 1
		while alpha < omega:
			if alpha & 1:
				res = self.func(res, self.data[alpha])
				alpha += 1
			if omega & 1:
				omega -= 1
				res = self.func(res, self.data[omega])
			alpha >>= 1
			omega >>= 1
		return res

	def update(self, index, value):
		index += self.size
		self.data[index] = value
		index >>= 1
		while index:
			self.data[index] = self.func(self.data[2 * index], self.data[2 * index + 1])
			index >>= 1
from bisect import bisect_left, bisect_right

class Result:

	def __init__(self, index, value):
		self.index = index
		self.value = value

class BinarySearch:

	def __init__(self):
		pass

	@staticmethod
	def greater_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_right(func, num)
			if index == len(func):
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(omega) <= num:
				return Result(None, None)
			while alpha < omega:
				if func(alpha) > num:
					return Result(alpha, func(alpha))
				if omega == alpha + 1:
					return Result(omega, func(omega))
				mid = (alpha + omega) // 2
				if func(mid) > num:
					omega = mid
				else:
					alpha = mid

	@staticmethod
	def less_than(num: int, func, size: int=1):
		if isinstance(func, list):
			index = bisect_left(func, num) - 1
			if index == -1:
				return Result(None, None)
			else:
				return Result(index, func[index])
		else:
			(alpha, omega) = (0, size - 1)
			if func(alpha) >= num:
				return Result(None, None)
			while alpha < omega:
				if func(omega) < num:
					return Result(omega, func(omega))
				if omega == alpha + 1:
					return Result(alpha, func(alpha))
				mid = (alpha + omega) // 2
				if func(mid) < num:
					alpha = mid
				else:
					omega = mid
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 gcd, ceil

def pre(s):
	n = len(s)
	pi = [0] * n
	for i in range(1, n):
		j = pi[i - 1]
		while j and s[i] != s[j]:
			j = pi[j - 1]
		if s[i] == s[j]:
			j += 1
		pi[i] = j
	return pi

def prod(a):
	ans = 1
	for each in a:
		ans = ans * each
	return ans

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

def binary(x, length=16):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y
bs = BinarySearch()
for _ in range(int(input()) if True else 1):
	(n, k) = map(int, input().split())
	x = sorted(list(map(int, input().split())))
	y = input()
	value = 0
	i = 0
	while i < n:
		alpha = i
		omega = bs.less_than(x[i] + 2 * k + 1, x).index
		value = max(value, omega - alpha + 1)
		i += 1
	kvals = []
	kinds = []
	i = 0
	while i < n:
		alpha = i
		omega = bs.less_than(x[i] + k + 1, x).index
		kvals += [omega - alpha + 1]
		kinds += [omega + 1]
		i += 1
	st = SegmentTree(kvals, func=max)
	value2 = 0
	for i in range(n):
		value2 = max(value2, kvals[i] + st.query(kinds[i], n - 1) if kinds[i] <= n - 1 else 0)
	print(max(value, value2))


from collections import defaultdict, deque, Counter
from heapq import heapify, heappop, heappush
import math
from copy import deepcopy
from itertools import combinations, permutations, product, combinations_with_replacement
from bisect import bisect_left, bisect_right
import sys

def input():
	return sys.stdin.readline().rstrip()

def getN():
	return int(input())

def getNM():
	return map(int, input().split())

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

def getListGraph():
	return list(map(lambda x: int(x) - 1, input().split()))

def getArray(intn):
	return [int(input()) for i in range(intn)]
mod = 10 ** 9 + 7
MOD = 998244353
inf = float('inf')
eps = 10 ** (-10)
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
T = getN()
for _ in range(T):
	(N, K) = getNM()
	X = getList()
	_ = getList()
	X.sort()
	r = 0
	rec_r = [0] * N
	for l in range(N):
		while r < N and X[r] - X[l] <= K:
			r += 1
		rec_r[l] = r - l
	l = N - 1
	rec_l = [0] * N
	for r in range(N - 1, -1, -1):
		while l >= 0 and X[r] - X[l] <= K:
			l -= 1
		rec_l[r] = r - l
	for i in range(N - 2, -1, -1):
		rec_r[i] = max(rec_r[i], rec_r[i + 1])
	for i in range(1, N):
		rec_l[i] = max(rec_l[i], rec_l[i - 1])
	(rec_r, rec_l) = (rec_r + [0], [0] + rec_l)
	ans = 0
	for i in range(N + 1):
		ans = max(ans, rec_r[i] + rec_l[i])
	print(ans)


from collections import defaultdict as dd
import sys
input = sys.stdin.readline
t = int(input())
while t:
	d = dd(int)
	(n, k) = map(int, input().split())
	x = list(map(int, input().split()))
	y = list(map(int, input().split()))
	for i in x:
		d[i] += 1
	x = []
	for i in d:
		x.append(i)
	x.sort()
	i = 0
	su = d[x[0]]
	j = 1
	le = 0
	n = len(x)
	di = []
	while i < n and j < n:
		if le + x[j] - x[j - 1] <= k:
			le += x[j] - x[j - 1]
			su += d[x[j]]
			j += 1
		else:
			di.append((su, j - 1))
			su -= d[x[i]]
			if i + 1 < n:
				le -= x[i + 1] - x[i]
			i += 1
	while i < n:
		di.append((su, n - 1))
		su -= d[x[i]]
		i += 1
	n = len(di)
	mx = [0] * n
	mx[-1] = di[-1][0]
	for i in range(n - 2, -1, -1):
		mx[i] = max(di[i][0], mx[i + 1])
	ans = 0
	for i in range(n):
		if di[i][1] + 1 < n:
			ans = max(ans, di[i][0] + mx[di[i][1] + 1])
		else:
			ans = max(ans, di[i][0])
	print(ans)
	t -= 1