Mishka received a gift of multicolored pencils for his birthday! Unfortunately he lives in a monochrome world, where everything is of the same color and only saturation differs. This pack can be represented as a sequence a_1, a_2, ..., a_{n} of n integer numbers — saturation of the color of each pencil. Now Mishka wants to put all the mess in the pack in order. He has an infinite number of empty boxes to do this. He would like to fill some boxes in such a way that:

  Each pencil belongs to exactly one box;  Each non-empty box has at least k pencils in it;  If pencils i and j belong to the same box, then |a_{i} - a_{j}| ≤ d, where |x| means absolute value of x. Note that the opposite is optional, there can be pencils i and j such that |a_{i} - a_{j}| ≤ d and they belong to different boxes. 

Help Mishka to determine if it's possible to distribute all the pencils into boxes. Print "YES" if there exists such a distribution. Otherwise print "NO".


-----Input-----

The first line contains three integer numbers n, k and d (1 ≤ k ≤ n ≤ 5·10^5, 0 ≤ d ≤ 10^9) — the number of pencils, minimal size of any non-empty box and maximal difference in saturation between any pair of pencils in the same box, respectively.

The second line contains n integer numbers a_1, a_2, ..., a_{n} (1 ≤ a_{i} ≤ 10^9) — saturation of color of each pencil.


-----Output-----

Print "YES" if it's possible to distribute all the pencils into boxes and satisfy all the conditions. Otherwise print "NO".


-----Examples-----
Input
6 3 10
7 2 7 7 4 2

Output
YES

Input
6 2 3
4 5 3 13 4 10

Output
YES

Input
3 2 5
10 16 22

Output
NO



-----Note-----

In the first example it is possible to distribute pencils into 2 boxes with 3 pencils in each with any distribution. And you also can put all the pencils into the same box, difference of any pair in it won't exceed 10.

In the second example you can split pencils of saturations [4, 5, 3, 4] into 2 boxes of size 2 and put the remaining ones into another box.

Difficulty: HARD
Tags: Sorting

Amortized analysis

Greedy algorithms

Dynamic programming

Data structures
Skill types: Sorting

Amortized analysis

Greedy algorithms

Dynamic programming

Data structures

Starter code:

Solutions:
import sys, math, queue
MOD = 998244353
sys.setrecursionlimit(1000000)

def check(i):
	if not dp[i][2]:
		return False
	if i < 0:
		return True
	return check(i - dp[i][1])
(n, k, d) = map(int, input().split())
if k == 1:
	print('YES')
	return
a = sorted(map(int, input().split()))
dp = [None for i in range(n)]
dp[0] = (a[0], 1, False)
for i in range(1, n):
	if a[i] - dp[i - 1][0] <= d:
		dp[i] = (dp[i - 1][0], dp[i - 1][1] + 1, dp[i - 1][1] + 1 >= k)
	else:
		dp[i] = (a[i], 1, False)
		j = i
		while a[i] - a[j] <= d and j > 0:
			j -= 1
			if dp[j][2]:
				dp[i] = (a[j + 1], i - j, i - j >= k)
			if dp[i][2]:
				break
print('YES' if check(n - 1) else 'NO')


import heapq

def run():
	(n, k, d) = map(int, input().split())
	a = sorted(map(int, input().split()))
	max_size = [None] * n
	start = 0
	end = 0
	while start < n:
		while end < n - 1 and a[end + 1] - a[start] <= d:
			end += 1
		max_size[start] = end - start + 1
		start += 1
	possilbe_starts = []
	heapq.heappush(possilbe_starts, (0, 'start'))
	heapq.heappush(possilbe_starts, (1, 'stop'))
	number_of_opened = 0
	for pencil in range(n):
		while possilbe_starts and possilbe_starts[0][0] <= pencil:
			top = heapq.heappop(possilbe_starts)
			number_of_opened += 1 if top[1] == 'start' else -1
		if number_of_opened <= 0:
			continue
		if max_size[pencil] < k:
			continue
		if pencil + max_size[pencil] + 1 > n:
			print('YES')
			break
		heapq.heappush(possilbe_starts, (pencil + k, 'start'))
		heapq.heappush(possilbe_starts, (pencil + max_size[pencil] + 1, 'stop'))
	else:
		print('NO')
run()


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

def getTransIntList(n):
	first = getIntList()
	m = len(first)
	result = [[0] * n for _ in range(m)]
	for i in range(m):
		result[i][0] = first[i]
	for j in range(1, n):
		curr = getIntList()
		for i in range(m):
			result[i][j] = curr[i]
	return result
(n, k, d) = getIntList()
a = getIntList()
a.sort()
cuttable = [False] * len(a)
cuttable[0] = True

def search(a):
	curr = 0
	upLim = 0
	upLimPrev = 0
	while True:
		if cuttable[curr]:
			lowLim = curr + k
			upLimPrev = upLim
			while upLim < len(a) and a[upLim] - a[curr] <= d:
				upLim += 1
			if upLim == len(a):
				return True
			lowLim = max(lowLim, upLimPrev + 1)
			for i in range(lowLim, upLim + 1):
				cuttable[i] = True
		curr += 1
		if curr > len(a) - k:
			break
	return False
if k == 1:
	print('YES')
elif search(a):
	print('YES')
else:
	print('NO')


(n, k, d) = list(map(int, input().split()))
a = sorted(list(map(int, input().split())))
b = [0] * n
i = j = 0
for i in range(n):
	while a[i] - a[j] > d:
		j += 1
	b[i] = j
c = [0] * n
for i in range(k - 1, n):
	c[i] = c[i - 1] + int(i - b[i] + 1 >= k and (b[i] == 0 or c[i - k] > c[b[i] - 2] or (b[i] == 1 and c[i - k] > c[0])))
print('YES' if n < 2 or c[n - 1] > c[n - 2] else 'NO')


from bisect import bisect_right, bisect_left

def main():
	(n, k, d) = map(int, input().split())
	sat = [int(x) for x in input().split()]
	sat = sorted(sat)
	arrange = [False for _ in range(n + 1)]
	arrange[0] = True
	s = 0
	i = min(bisect_right(sat, sat[s] + d), k)
	n_arrange = 1 if i - k >= 0 else 0
	while i <= n:
		if i - s >= k and n_arrange > 0:
			arrange[i] = True
		if i < n:
			news = bisect_left(sat, sat[i] - d, s, i)
			while s < news:
				if s <= i - k and arrange[s]:
					n_arrange -= 1
				s += 1
		i += 1
		n_arrange += 1 if i - k >= s and arrange[i - k] else 0
	if arrange[n]:
		print('YES')
	else:
		print('NO')

def __starting_point():
	main()
__starting_point()


from bisect import bisect
from sys import exit
[n, k, d] = map(int, input().strip().split())
ais = list(map(int, input().strip().split()))
if k == 1:
	print('YES')
	exit()
ais.sort()
cando = [False for _ in range(n)]
j = n - 1
count = 0
for i in reversed(range(n)):
	if i + k < n and cando[i + k]:
		count += 1
	if n - i < k:
		continue
	if ais[-1] - ais[i] <= d:
		cando[i] = True
		continue
	while ais[j - 1] > ais[i] + d:
		if cando[j]:
			count -= 1
		j -= 1
	cando[i] = count > 0
if cando[0]:
	print('YES')
else:
	print('NO')


import bisect
import sys
input = sys.stdin.readline

class SegmentTree:

	def __init__(self, n, op, e):
		self.n = n
		self.op = op
		self.e = e
		self.size = 2 ** (n - 1).bit_length()
		self.node = [self.e] * (2 * self.size)

	def built(self, array):
		for i in range(self.n):
			self.node[self.size + i] = array[i]
		for i in range(self.size - 1, 0, -1):
			self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])

	def update(self, i, val):
		i += self.size
		self.node[i] = val
		while i > 1:
			i >>= 1
			self.node[i] = self.op(self.node[i << 1], self.node[(i << 1) + 1])

	def get_val(self, l, r):
		(l, r) = (l + self.size, r + self.size)
		(res_l, res_r) = (self.e, self.e)
		while l < r:
			if l & 1:
				res_l = self.op(res_l, self.node[l])
				l += 1
			if r & 1:
				r -= 1
				res_r = self.op(self.node[r], res_r)
			(l, r) = (l >> 1, r >> 1)
		return self.op(res_l, res_r)
(n, k, d) = map(int, input().split())
a = list(map(int, input().split()))
a = sorted(a)
st = SegmentTree(n + 1, lambda a, b: a | b, 0)
st.update(0, 1)
for i in range(n):
	tmp = bisect.bisect_left(a, a[i] - d)
	if tmp >= max(i + 2 - k, 0):
		continue
	st.update(i + 1, st.get_val(tmp, max(i + 2 - k, 0)))
if st.get_val(n, n + 1) == 1:
	print('YES')
else:
	print('NO')


(n, k, d) = map(int, input().split())
A = sorted(map(int, input().split()))
can_do = [0] * (n + 1)
can_do[0] = 1
(l, r) = (0, 0)
for (i, a) in enumerate(A, start=1):
	while a - d > A[l]:
		l += 1
	r = i - k
	can = 0
	if r >= l:
		s = can_do[r]
		if l:
			s -= can_do[l - 1]
		if s > 0:
			can = 1
	can_do[i] = can_do[i - 1] + can
print('YES' if can_do[n] - can_do[n - 1] > 0 else 'NO')


import bisect

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

def getTransIntList(n):
	first = getIntList()
	m = len(first)
	result = [[0] * n for _ in range(m)]
	for i in range(m):
		result[i][0] = first[i]
	for j in range(1, n):
		curr = getIntList()
		for i in range(m):
			result[i][j] = curr[i]
	return result
(n, k, d) = getIntList()
a = getIntList()
a.sort()
seen = [False] * len(a)

def search(a, lowLim):
	sameLim = bisect.bisect_right(a, a[lowLim] + d)
	lowLim = max(lowLim, sameLim - 2 * k)
	if seen[lowLim]:
		return False
	if len(a) - lowLim < k:
		return False
	if a[len(a) - 1] - a[lowLim] <= d:
		return True
	for i in range(lowLim + k - 1, len(a) - 1):
		if a[i] - a[lowLim] > d:
			break
		if search(a, i + 1):
			return True
	seen[lowLim] = True
	return False

def searchFull(a):
	if a[n - 1] - a[n - k] > d:
		return False
	return search(a, 0)
if k == 1:
	print('YES')
elif searchFull(a):
	print('YES')
else:
	print('NO')


import sys
(n, k, d) = map(int, input().split())
a = [0] + sorted(map(int, input().split()))
dp = [1] + [0] * n
j = k
for i in range(n):
	if dp[i] == 0:
		continue
	j = max(j, i + k)
	while j <= n and a[j] - a[i + 1] <= d:
		dp[j] |= dp[i]
		j += 1
print('YES' if dp[-1] else 'NO')


from bisect import bisect

def main():
	(n, k, d) = list(map(int, input().split()))
	if k == 1:
		print('YES')
		return
	l = []
	ll = [l]
	a = 10 ** 10
	for b in sorted(map(int, input().split())):
		if a < b:
			if len(l) < k:
				print('NO')
				return
			l = [b]
			ll.append(l)
		else:
			l.append(b)
		a = b + d

	def f(a):

		def dfs(i):
			avail[i] = False
			if i + k <= le:
				if a[-1] <= a[i] + d:
					raise TabError
				j = bisect(a, a[i] + d, i, -1) - 1
				for j in range(bisect(a, a[i] + d, i, -1), i + k - 1, -1):
					if avail[j]:
						dfs(j)
		le = len(a)
		avail = [True] * le
		try:
			dfs(0)
		except TabError:
			return True
		return False
	print(('NO', 'YES')[all(map(f, ll))])

def __starting_point():
	main()
__starting_point()


def main():
	import sys
	from bisect import bisect_left
	input = sys.stdin.readline
	(N, K, D) = map(int, input().split())
	A = list(map(int, input().split()))
	A.sort()
	part = [0] * (N + 2)
	part[0] = 1
	part[1] = -1
	for (i, a) in enumerate(A):
		part[i] += part[i - 1]
		if part[i]:
			j = bisect_left(A, a + D + 1)
			if j >= i + K:
				part[i + K] += 1
				part[j + 1] -= 1
	part[N] += part[N - 1]
	if part[N]:
		print('YES')
	else:
		print('NO')
main()


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

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class TreeNode:

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

class AvlTree:

	def __init__(self):
		self._tree = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class SegmentTree1:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class SegmentTree:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class Factorial:

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

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

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

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

class Combination:

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

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

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

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

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

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = (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 = l + (r - l) // 2
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater

class TrieNode:

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

class Trie:

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

	def getNode(self):
		return TrieNode()

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

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

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

class Node:

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

class BinaryTrie:

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

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

	def query(self, xor):
		self.temp = self.root
		for i in range(31, -1, -1):
			val = xor & 1 << i
			if not val:
				if self.temp.left and self.temp.left.count > 0:
					self.temp = self.temp.left
				elif self.temp.right:
					self.temp = self.temp.right
			elif self.temp.right and self.temp.right.count > 0:
				self.temp = self.temp.right
			elif self.temp.left:
				self.temp = self.temp.left
			self.temp.count -= 1
		return xor ^ self.temp.data
(n, k, d) = map(int, input().split())
l = list(map(int, input().split()))
l.sort()
l = [l[0]] + l
n += 1
dp = [0 for i in range(n)]
dp[0] = 1
s = SegmentTree(dp)
for i in range(1, n):
	e = binarySearchCount(l, n, l[i] - d)
	st = i - k
	e -= 1
	if e > st:
		dp[i] = 0
	else:
		we = s.query(e, st)
		dp[i] = we
	s.__setitem__(i, dp[i])
if dp[n - 1] == 0:
	print('NO')
else:
	print('YES')


import sys
readline = sys.stdin.readline

class Segtree:

	def __init__(self, A, intv, initialize=True, segf=max):
		self.N = len(A)
		self.N0 = 2 ** (self.N - 1).bit_length()
		self.intv = intv
		self.segf = segf
		if initialize:
			self.data = [intv] * self.N0 + A + [intv] * (self.N0 - self.N)
			for i in range(self.N0 - 1, 0, -1):
				self.data[i] = self.segf(self.data[2 * i], self.data[2 * i + 1])
		else:
			self.data = [intv] * (2 * self.N0)

	def update(self, k, x):
		k += self.N0
		self.data[k] = x
		while k > 0:
			k = k >> 1
			self.data[k] = self.segf(self.data[2 * k], self.data[2 * k + 1])

	def query(self, l, r):
		(L, R) = (l + self.N0, r + self.N0)
		s = self.intv
		while L < R:
			if R & 1:
				R -= 1
				s = self.segf(s, self.data[R])
			if L & 1:
				s = self.segf(s, self.data[L])
				L += 1
			L >>= 1
			R >>= 1
		return s

	def binsearch(self, l, r, check, reverse=False):
		(L, R) = (l + self.N0, r + self.N0)
		(SL, SR) = ([], [])
		while L < R:
			if R & 1:
				R -= 1
				SR.append(R)
			if L & 1:
				SL.append(L)
				L += 1
			L >>= 1
			R >>= 1
		if reverse:
			for idx in SR + SL[::-1]:
				if check(self.data[idx]):
					break
			else:
				return -1
			while idx < self.N0:
				if check(self.data[2 * idx + 1]):
					idx = 2 * idx + 1
				else:
					idx = 2 * idx
			return idx - self.N0
		else:
			for idx in SL + SR[::-1]:
				if check(self.data[idx]):
					break
			else:
				return -1
			while idx < self.N0:
				if check(self.data[2 * idx]):
					idx = 2 * idx
				else:
					idx = 2 * idx + 1
			return idx - self.N0
(N, K, D) = list(map(int, readline().split()))
A = list(map(int, readline().split()))
A.sort()
lm = [None] * N
for i in range(N):
	a = A[i]
	ok = i
	ng = -1
	while abs(ok - ng) > 1:
		med = (ok + ng) // 2
		if a - A[med] <= D:
			ok = med
		else:
			ng = med
	lm[i] = ok
T = Segtree([None] * (N + 1), 0, initialize=False, segf=max)
T.update(0, 1)
for i in range(N):
	rm = i - K + 2
	if rm <= lm[i]:
		continue
	if T.query(lm[i], rm):
		T.update(i + 1, 1)
print('YES' if T.query(N, N + 1) else 'NO')


def bi_search(a, x):
	n = len(a)
	(u, l) = (n, -1)
	while u - l > 1:
		md = (u + l) // 2
		if x > a[md]:
			l = md
		else:
			u = md
	return u

class Bit:

	def __init__(self, n):
		self.bit = [0] * (n + 1)
		self.n = n

	def sum_prefix(self, i):
		s = 0
		while i > 0:
			s += self.bit[i]
			i -= i & -i
		return s

	def sum_(self, l, r):
		if l == 1:
			return self.sum_prefix(r)
		return self.sum_prefix(r) - self.sum_prefix(l - 1)

	def add(self, i, x):
		while i <= self.n:
			self.bit[i] += x
			i += i & -i
(n, k, d) = map(int, input().split())
a = [-1] + list(map(int, input().split()))
a = sorted(a)
B = Bit(n)
ans = [-1] * n
for i in range(n + 1):
	if i == 0:
		continue
	pos = bi_search(a, max(0, a[i] - d))
	(l, r) = (pos - 1, i - k)
	if l <= r:
		s = 0
		if l >= 1:
			s += B.sum_(l, r)
		if l == 0 or s > 0:
			B.add(i, 1)
			ans[i - 1] = 1
if ans[-1] == 1:
	print('YES')
else:
	print('NO')