Kefa wants to celebrate his first big salary by going to restaurant. However, he needs company. 

Kefa has n friends, each friend will agree to go to the restaurant if Kefa asks. Each friend is characterized by the amount of money he has and the friendship factor in respect to Kefa. The parrot doesn't want any friend to feel poor compared to somebody else in the company (Kefa doesn't count). A friend feels poor if in the company there is someone who has at least d units of money more than he does. Also, Kefa wants the total friendship factor of the members of the company to be maximum. Help him invite an optimal company!


-----Input-----

The first line of the input contains two space-separated integers, n and d (1 ≤ n ≤ 10^5, $1 \leq d \leq 10^{9}$) — the number of Kefa's friends and the minimum difference between the amount of money in order to feel poor, respectively.

Next n lines contain the descriptions of Kefa's friends, the (i + 1)-th line contains the description of the i-th friend of type m_{i}, s_{i} (0 ≤ m_{i}, s_{i} ≤ 10^9) — the amount of money and the friendship factor, respectively. 


-----Output-----

Print the maximum total friendship factir that can be reached.


-----Examples-----
Input
4 5
75 5
0 100
150 20
75 1

Output
100

Input
5 100
0 7
11 32
99 10
46 8
87 54

Output
111



-----Note-----

In the first sample test the most profitable strategy is to form a company from only the second friend. At all other variants the total degree of friendship will be worse.

In the second sample test we can take all the friends.

Difficulty: MEDIUM
Tags: Sorting

Amortized analysis
Skill types: Sorting

Amortized analysis

Starter code:

Solutions:
(n, d) = map(int, input().split())
l_p = list()
for _ in range(n):
	l_p.append(list(map(int, input().split())))
l_p.sort()
(l, h) = (0, 0)
f = 0
f_m = 0
while h < len(l_p):
	if l_p[h][0] - l_p[l][0] >= d:
		f -= l_p[l][1]
		l += 1
	else:
		f += l_p[h][1]
		h += 1
	f_m = max(f_m, f)
print(f_m)


def answer(n, d, A):
	A.sort(key=lambda x: x[0])
	pre = [0] * (n + 1)
	for i in range(1, n + 1):
		pre[i] = pre[i - 1] + A[i - 1][1]
	l = 0
	r = 0
	maxi = 0
	while r >= l and r < n:
		if A[r][0] - A[l][0] < d:
			r += 1
		else:
			maxi = max(maxi, pre[r] - pre[l])
			l += 1
	maxi = max(maxi, pre[r] - pre[l])
	return maxi
(n, d) = map(int, input().split())
arr = []
for i in range(n):
	(v, f) = map(int, input().split())
	arr.append([v, f])
print(answer(n, d, arr))


import sys
from bisect import bisect_right
from itertools import accumulate

def main():
	(n, d) = map(int, input().split())
	friends = sorted((tuple((int(c) for c in line.split())) for line in sys.stdin))
	money = [e[0] for e in friends]
	friendship_sum = [0] + list(accumulate((e for (_, e) in friends)))
	start = 0
	(_min, ans) = friends[0]
	for i in range(1, n):
		cur = friends[i][0]
		if cur - _min >= d:
			start = bisect_right(money, cur - d)
			_min = friends[start][0]
		friendship = friendship_sum[i + 1] - friendship_sum[start]
		ans = max(ans, friendship)
	print(ans)
main()


def kac(l, d):
	l.sort(reverse=True)
	ma = l[0][1]
	v = l[0][1]
	i = j = 0
	for i in range(1, len(l)):
		v = v + l[i][1]
		while abs(l[i][0] - l[j][0]) >= d:
			v -= l[j][1]
			j += 1
		if v > ma:
			ma = v
	print(ma)
	return
(n, d) = map(int, input().split())
l1 = []
for i in range(n):
	m = list(map(int, input().split()))
	l1.append(m)
kac(l1, d)


(n, d) = (int(x) for x in input().split())
ms = []
for _ in range(n):
	ms.append(tuple((int(x) for x in input().split())))
ms.sort()
ans = 0
(start, end, ssum) = (0, 0, 0)
while end < n:
	end += 1
	ssum += ms[end - 1][1]
	while start < end and ms[end - 1][0] >= ms[start][0] + d:
		ssum -= ms[start][1]
		start += 1
	ans = max(ans, ssum)
print(ans)


(n, m) = map(int, input().split())
matrix = []
ans = -1000000
kol = 0
for i in range(n):
	(a, b) = map(int, input().split())
	matrix.append((a, b))
matrix.sort()
pr = [0]
for i in range(n):
	pr.append(matrix[i][1] + pr[-1])
for i in range(n):
	kol = 0
	s = matrix[i][1]
	cost = matrix[i][0]
	l = i
	r = n
	while l + 1 < r:
		mi = (l + r) // 2
		if matrix[mi][0] - cost < m:
			l = mi
		else:
			r = mi
	ans = max(ans, pr[l + 1] - pr[i])
print(ans)


(n, d) = list(map(int, input().rstrip().split()))
li = []
for i in range(n):
	li += [list(map(int, input().rstrip().split()))]
li.sort(key=lambda x: x[0])
j = 0
f = 0
ans = li[0][1]
i = 0
while i < n:
	while li[i][0] - li[j][0] >= d:
		f -= li[j][1]
		j += 1
	f += li[i][1]
	ans = max(ans, f)
	i += 1
print(ans)


(n, m) = map(int, input().split())
ls = [list(map(int, input().split())) for i in range(n)]
ls.sort(reverse=True)
(su, maximum) = (0, 0)
su = ls[0][1]
maximum = su
top = 0
i = 1
while i < n:
	while i < n and ls[i][0] + m > ls[top][0]:
		su += ls[i][1]
		i += 1
	maximum = max(maximum, su)
	if i == n:
		break
	while i > top and ls[i][0] + m <= ls[top][0]:
		su -= ls[top][1]
		top += 1
	su += ls[i][1]
	maximum = max(maximum, su)
	i += 1
print(maximum)


(z, zz) = (input, lambda : list(map(int, z().split())))
zzz = lambda : [int(i) for i in stdin.readline().split()]
(szz, graph, mod, szzz) = (lambda : sorted(zz()), {}, 10 ** 9 + 7, lambda : sorted(zzz()))
from string import *
from re import *
from collections import *
from queue import *
from sys import *
from collections import *
from math import *
from heapq import *
from itertools import *
from bisect import *
from collections import Counter as cc
from math import factorial as f
from bisect import bisect as bs
from bisect import bisect_left as bsl
from itertools import accumulate as ac

def lcd(xnum1, xnum2):
	return xnum1 * xnum2 // gcd(xnum1, xnum2)

def prime(x):
	p = ceil(x ** 0.5) + 1
	for i in range(2, p):
		if x % i == 0 and x != 2 or x == 0:
			return 0
	return 1

def dfs(u, visit, graph):
	visit[u] = True
	for i in graph[u]:
		if not visit[i]:
			dfs(i, visit, graph)
(n, d) = zzz()
li = []
for _ in range(n):
	li.append(zz())
li = sorted(li)
s = ans = li[0][1]
j = 0
for i in range(1, n):
	while li[i][0] - li[j][0] >= d:
		s -= li[j][1]
		j += 1
	s += li[i][1]
	ans = max(s, ans)
print(ans)


def main():
	(n, d) = map(int, input().split())
	ms = []
	for i in range(n):
		ms.append(list(map(int, input().split())))
	ms.sort()
	hr = 0
	hl = 0
	mini = ms[0][0]
	sumi = 0
	s = 0
	while hr < n:
		mini = ms[hr][0]
		while hl < n and ms[hl][0] - mini < d:
			s += ms[hl][1]
			hl += 1
		if s > sumi:
			sumi = s
		s -= ms[hr][1]
		hr += 1
	print(sumi)
main()


(n, d) = map(int, input().split())
a = []
for i in range(n):
	a.append([int(i) for i in input().split()])
a.sort()
money = 0
f = a[0][1]
ff = []
for i in range(1, n):
	if a[i][0] < a[money][0] + d:
		f += a[i][1]
	else:
		ff.append(f)
		while a[i][0] >= a[money][0] + d:
			f -= a[money][1]
			money += 1
		f += a[i][1]
ff.append(f)
print(max(ff))


(n, d) = map(int, input().split())
friends = sorted((list(map(int, input().split())) for _ in range(n)))
(friendship, highest, i) = (0, 0, 0)
for j in range(n):
	friendship += friends[j][1]
	while friends[j][0] - friends[i][0] >= d:
		friendship -= friends[i][1]
		i += 1
	highest = max(highest, friendship)
print(highest)


def key_tri(argument):
	return argument[0]
(n, d) = list(map(int, input().split()))
L = [list(map(int, input().split())) for _ in range(n)]
L.sort(key=key_tri)
deb = 0
T = []
s = 0
for k in range(1, n):
	if L[k][0] - L[deb][0] >= d:
		s = 0
		for i in range(deb, k):
			s += L[i][1]
		T += [s]
		s = deb + 1
		while L[k][0] - L[s][0] >= d:
			s += 1
		deb = s
s = 0
for k in range(deb, n):
	s += L[k][1]
T = T + [s]
print(max(T))


from collections import namedtuple
from operator import itemgetter
Friend = namedtuple('Friend', 'm s')
(n, d) = map(int, input().split())
f = []
for i in range(n):
	f.append(Friend(*map(int, input().split())))
f.sort(key=itemgetter(0))
left = 0
cur = f[0].s
result = cur
for (i, fr) in enumerate(f[1:], 1):
	while left < i and f[left].m + d <= fr.m:
		cur -= f[left].s
		left += 1
	cur += fr.s
	result = max(result, cur)
print(result)


(n, m) = tuple((int(x) for x in input().split()))
v = []
for i in range(n):
	i = input()
	v.append(tuple((int(x) for x in i.split())))
v.sort(reverse=True)
maxi = val = v[0][1]
i = j = 0
for j in range(1, len(v)):
	val += v[j][1]
	while abs(v[j][0] - v[i][0]) >= m:
		val -= v[i][1]
		i += 1
	if val > maxi:
		maxi = val
print(maxi)


def solve(n, d, friends):
	big = float('inf')
	small = float('-inf')
	friends.sort()
	maxer = small
	f = 0
	s = 0
	ind = 0
	curr = 0
	while ind < n:
		last = 0
		miner = friends[s][0]
		while s < n and abs(friends[ind][0] - friends[s][0]) >= d:
			curr -= friends[s][1]
			s += 1
			miner = friends[s][0]
		flag = True
		while ind < n and abs(friends[ind][0] - miner) < d:
			curr += friends[ind][1]
			ind += 1
			flag = False
		if flag:
			curr += friends[ind][1] + last
			ind += 1
		maxer = max(maxer, curr - last)
	return maxer

def main():
	d = input()
	d = [int(i) for i in d.split()]
	a = d[0]
	b = d[1]
	friends = []
	for i in range(a):
		d = input()
		d = [int(i) for i in d.split()]
		m = d[0]
		f = d[1]
		friends.append((m, f))
	ans = solve(a, b, friends)
	print(ans)
main()


(n, d) = [int(i) for i in input().split()]
a = [0] * n
for i in range(n):
	a[i] = [int(j) for j in input().split()]
a.sort()
i = 0
j = 0
ans = 0
c = 0
for j in range(0, n):
	if j > 0:
		c -= a[j - 1][1]
	while i < n:
		if a[i][0] - a[j][0] < d:
			c += a[i][1]
			i += 1
		else:
			break
	ans = max(c, ans)
print(ans)


(n, d) = map(int, input().strip().split())
arr = [tuple(map(int, input().strip().split())) for i in range(n)]
arr.sort()
last = 0
max_score = 0
curr_score = 0
for (money, friendship) in arr:
	if money >= last + d:
		max_score = max(max_score, curr_score)
		curr_score = friendship
		last = money
	else:
		curr_score += friendship
max_score = max(max_score, curr_score)
print(max_score)


(n, d) = map(int, input().split())
friends = []
for i in range(n):
	(money, factor) = map(int, input().split())
	friends.append([money, factor])
friends.sort()
ans = 0
tmp_ans = friends[0][1]
back = 0
front = 1
while front < n:
	if friends[front][0] - friends[back][0] < d:
		tmp_ans += friends[front][1]
		front += 1
	else:
		if tmp_ans > ans:
			ans = tmp_ans
		while friends[front][0] - friends[back][0] >= d:
			tmp_ans -= friends[back][1]
			back += 1
		if back == front:
			tmp_ans += friends[back][1]
			front += 1
if tmp_ans > ans:
	ans = tmp_ans
print(ans)


import itertools as ittls
from collections import Counter

def sqr(x):
	return x * x

def inputarray(func=int):
	return map(func, input().split())
(N, d) = map(int, input().split())
A = [(None, None)] * N
for i in range(N):
	A[i] = tuple(map(int, input().split()))
A.sort(key=lambda x: x[0])
prefix = [0] + [None] * len(A)
for (i, (money, friendship)) in enumerate(A):
	prefix[i + 1] = prefix[i] + friendship
(res, i, j) = (0, 0, 0)
while i < len(A):
	while j < len(A) and A[j][0] < A[i][0] + d:
		j = j + 1
	if prefix[j] - prefix[i] > res:
		res = prefix[j] - prefix[i]
	i = i + 1
print(res)


(n, d) = list(map(int, input().split()))
arr = []
for i in range(n):
	(x, y) = list(map(int, input().split()))
	arr.append([x, y])
arr.sort()
s = 0
temp = 0
maxVal = 0
for i in range(n):
	s += arr[i][1]
	while arr[i][0] - arr[temp][0] >= d:
		s -= arr[temp][1]
		temp += 1
	maxVal = max(maxVal, s)
print(maxVal)


line = [int(s) for s in input().split(' ')]
nr_friends = line[0]
friends = []
d = line[1]
for i in range(nr_friends):
	line = [int(s) for s in input().split(' ')]
	friends.append(line)
friends.sort()
max_sum = friends[0][1]
curr_sum = max_sum
remember = 0
i = 1
j = 0
while i < len(friends):
	if abs(friends[i][0] - friends[j][0]) < d:
		curr_sum += friends[i][1]
	else:
		while abs(friends[i][0] - friends[j][0]) >= d:
			curr_sum -= friends[j][1]
			j += 1
		curr_sum += friends[i][1]
	i += 1
	max_sum = max(max_sum, curr_sum)
print(max_sum)


from sys import stdin
a = lambda : stdin.readline().split()
(n, d) = map(int, a())
di = {-1: 0}
for _ in range(n):
	(m, s) = map(int, a())
	if di.get(m) == None:
		di[m] = 0
	di[m] += s
lst = [*di.keys()]
lst.sort()
for (i, x) in enumerate(lst[1:]):
	di[x] += di[lst[i]]
from bisect import bisect_left as bis
res = 0
for (i, x) in enumerate(lst[1:]):
	item = bis(lst, x + d) - 1
	res = max(res, di[lst[item]] - di[lst[i]])
print(res)


(n, k) = map(int, input().split())
l = [list(map(int, input().split())) for i in range(n)]
l.sort(key=lambda x: x[0])
val = l[0][0]
i = 0
j = i + 1
ans = 0
temp = l[i][1]
while j < n and l[j][0] - l[i][0] < k:
	temp += l[j][1]
	j += 1
ans = max(ans, temp)
while j < n:
	if j < n and i < n and (l[j][0] - l[i][0] < k):
		temp += l[j][1]
		ans = max(ans, temp)
		j += 1
	elif j < n and i < n:
		temp -= l[i][1]
		i += 1
		ans = max(ans, temp)
print(ans)


(n, d) = map(int, input().split())
money = []
dic = {}
for _ in range(n):
	(m, s) = map(int, input().split())
	money.append(m)
	if m in dic:
		dic[m].append(s)
	else:
		dic[m] = [s]
money.sort()
f = []
money1 = sorted(list(set(money)))
for i in money1:
	for j in dic[i]:
		f.append(j)
money = [None] + money
f = [None] + f
pref = [0 for i in range(n + 1)]
for i in range(1, n + 1):
	pref[i] = f[i] + pref[i - 1]
i = 1
j = 1
final = []
while j <= n and i <= n:
	if money[j] - money[i] < d:
		if j == n:
			final.append(pref[j] - pref[i - 1])
		j += 1
	else:
		final.append(pref[j - 1] - pref[i - 1])
		i += 1
print(max(final))


(n, d) = list(map(int, input().split()))
friends = []
max_friendship = 0
tmp_index = 0
tmp_friendship = 0
for k in range(n):
	(m, s) = list(map(int, input().split()))
	friends.append({'m': m, 's': s})
friends = sorted(friends, key=lambda x: x['m'])
k = 0
while k < n:
	if abs(friends[tmp_index]['m'] - friends[k]['m']) >= d:
		tmp_friendship -= friends[tmp_index]['s']
		tmp_index += 1
	else:
		tmp_friendship += friends[k]['s']
		max_friendship = max(max_friendship, tmp_friendship)
		k += 1
print(max_friendship)


(n, d) = map(int, input().split())
a = sorted([list(map(int, input().split())) for i in range(n)])
left = 0
cur_sum = 0
max_sum = 0
for right in range(n):
	cur_sum += a[right][1]
	while a[right][0] - a[left][0] >= d:
		cur_sum -= a[left][1]
		left += 1
	if cur_sum > max_sum:
		max_sum = cur_sum
print(max_sum)


(n, d) = list(map(int, input().split()))
persons = []
for i in range(n):
	(m, s) = list(map(int, input().split()))
	persons.append((m, s))
persons.sort()
max_s = 0
cur_s = persons[0][1]
good_persons = [persons[0]]
for i in range(1, n):
	if abs(good_persons[0][0] - persons[i][0]) < d:
		good_persons.append(persons[i])
		cur_s += persons[i][1]
	else:
		j = 0
		rec_s = 0
		while j < len(good_persons) and abs(good_persons[j][0] - persons[i][0]) >= d:
			rec_s += good_persons[j][1]
			j += 1
		if rec_s <= persons[i][1]:
			cur_s = cur_s - rec_s + persons[i][1]
			good_persons = good_persons[j:] + [persons[i]]
		else:
			max_s = max(max_s, cur_s)
			cur_s = cur_s - rec_s + persons[i][1]
			good_persons = good_persons[j:] + [persons[i]]
print(max(cur_s, max_s))


from operator import itemgetter
(n, d) = map(int, input().split())
fir = 0
sec = 0
ar = [list(map(int, input().split())) for i in range(n)]
ar.sort(key=itemgetter(0))
ans = ar[0][1]
ar2 = [0] * (n + 1)
for i in range(n):
	ar2[i + 1] = ar2[i] + ar[i][1]
while sec < n:
	if ar[sec][0] - ar[fir][0] >= d:
		fir += 1
	else:
		ans = max(ans, ar2[sec + 1] - ar2[fir])
		sec += 1
print(ans)


(n, d) = [int(x) for x in input().split()]
li = []
for i in range(n):
	l = list(map(int, input().split()))
	li.append(l)
li.sort()
lii = []
b = 0
for i in range(n):
	if i == 0:
		num = 0
	else:
		num = num - li[i - 1][1]
	a = 0
	for j in range(b, n):
		if li[j][0] < li[i][0] + d:
			num += li[j][1]
		else:
			a = 1
			b = j
			break
	if a == 0:
		b = n
	lii.append(num)
print(max(lii))


from sys import stdin, stdout
lines = stdin.readlines()
(n, d) = (int(lines[0].split()[0]), int(lines[0].split()[1]))
mat = [[int(x.split()[0]), int(x.split()[1])] for x in lines[1:]]
mat = sorted(mat)
mx = 0
temp_mx = 0
i = 0
for j in range(n):
	temp_mx += mat[j][1]
	if mat[j][0] - mat[i][0] >= d:
		while mat[j][0] - mat[i][0] >= d:
			temp_mx -= mat[i][1]
			i += 1
	mx = max(temp_mx, mx)
print(mx)


(n, d) = map(int, input().split())
p = []
for i in range(n):
	(m, f) = map(int, input().split())
	p.append([m, f])
p = sorted(p)
x2 = 0
max_f = 0
f = 0
for x1 in range(n):
	x2 = max(x1, x2)
	while x2 < n and p[x2][0] - p[x1][0] < d:
		f += p[x2][1]
		x2 += 1
	if f > max_f:
		max_f = f
	f -= p[x1][1]
print(max_f)


from sys import stdin, stdout
input = stdin.readline
(n, h) = map(int, input().split())
f = sorted([list(map(int, input().split())) for i in range(n)])
ans = 0
fc = f[0][1]
start = 0
for i in range(1, n):
	while f[i][0] - f[start][0] >= h:
		ans = max(ans, fc)
		fc -= f[start][1]
		start += 1
	fc += f[i][1]
	ans = max(ans, fc)
stdout.write(str(max(ans, fc)))


(n, d) = map(int, input().split())
friends = sorted((tuple(map(int, input().split())) for _ in range(n)))
left = sub_sum = max_sum = 0
for right in range(n):
	sub_sum += friends[right][1]
	while friends[right][0] - friends[left][0] >= d:
		(sub_sum, left) = (sub_sum - friends[left][1], left + 1)
	max_sum = max(sub_sum, max_sum)
print(max_sum)


import sys

def solve(input_path=None):
	if input_path is None:
		f = sys.stdin
	else:
		f = open(input_path, 'r')
	(n, d) = map(int, f.readline().split())
	candidates = list()
	for _ in range(n):
		(ab, at) = map(int, f.readline().split())
		candidates.append((ab, at))
	candidates = sorted(candidates)
	res = 0
	temp = 0
	(i, j) = (0, 0)
	while i < n and j < n:
		if candidates[j][0] - candidates[i][0] < d:
			temp += candidates[j][1]
			res = max(res, temp)
			j += 1
		else:
			temp -= candidates[i][1]
			i += 1
	return [f'{res}']

def main():
	for line in solve():
		print(f'{line}')
main()


line = input().split()
n = int(line[0])
d = int(line[1])
friends = list()
for i in range(n):
	line = input().split()
	friends.append([int(line[0]), int(line[1])])
friends.sort()
sum = friends[0][1]
sum_max = sum
baza = friends[0][0]
i = 1
j = 0
while i < len(friends) and j < len(friends):
	if friends[i][0] - friends[j][0] < d:
		sum = sum + friends[i][1]
		if sum > sum_max:
			sum_max = sum
		i += 1
	elif friends[i][1] > sum_max:
		sum_max = friends[i][1]
		sum = friends[i][1]
		j = i
		i += 1
	else:
		sum = sum - friends[j][1]
		j += 1
print(sum_max)


(n, d) = map(int, input().split())
arr = []
for i in range(n):
	arr.append(tuple(map(int, input().split())))
arr = sorted(arr)
prefix = []
prefix.append(arr[0][1])
for i in range(1, n):
	prefix.append(prefix[i - 1] + arr[i][1])
ans = 0
for i in range(n):
	low = 0
	high = n - 1
	while low < high:
		mid = (low + high + 1) // 2
		if arr[mid][0] >= arr[i][0] + d:
			high = mid - 1
		else:
			low = mid
	if i == 0:
		ans = prefix[low]
	elif prefix[low] - prefix[i - 1] > ans:
		ans = prefix[low] - prefix[i - 1]
print(ans)


import sys
import string
import math
from collections import defaultdict
from functools import lru_cache
from collections import Counter
from fractions import Fraction

def mi(s):
	return map(int, s.strip().split())

def lmi(s):
	return list(mi(s))

def tmi(s):
	return tuple(mi(s))

def mf(f, s):
	return map(f, s)

def lmf(f, s):
	return list(mf(f, s))

def js(lst):
	return ' '.join((str(d) for d in lst))

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

def linesp():
	return line().split()

def iline():
	return int(line())

def mat(n):
	matr = []
	for _ in range(n):
		matr.append(linesp())
	return matr

def matns(n):
	mat = []
	for _ in range(n):
		mat.append([c for c in line()])
	return mat

def mati(n):
	mat = []
	for _ in range(n):
		mat.append(lmi(line()))
	return mat

def pmat(mat):
	for row in mat:
		print(js(row))

def dist(x, y):
	return ((x[0] - y[0]) ** 2 + (x[1] - y[1]) ** 2) ** 0.5

def fast_exp(x, n):
	if n == 0:
		return 1
	elif n % 2 == 1:
		return x * fast_exp(x, (n - 1) // 2) ** 2
	else:
		return fast_exp(x, n // 2) ** 2

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

def bin_search(arr, diff, value, i):
	lo = i
	hi = len(arr) - 1
	while lo <= hi:
		if lo == hi:
			return lo
		elif lo == hi - 1:
			if arr[hi] - value < diff:
				return hi
			else:
				return lo
		mid = (lo + hi) // 2
		if arr[mid] - value < diff:
			lo = mid
		else:
			hi = mid

def main(n, diff, friends):
	friends.sort(key=lambda x: x[0])
	(money, factor) = zip(*friends)
	fact_pref = [factor[0]]
	for i in range(1, len(factor)):
		fact_pref.append(fact_pref[-1] + factor[i])
	happ = -float('inf')
	for i in range(len(friends)):
		(mon, _) = friends[i]
		best = bin_search(money, diff, mon, i)
		if i == 0:
			happ = max(happ, fact_pref[best])
		else:
			happ = max(happ, fact_pref[best] - fact_pref[i - 1])
	print(happ)
(n, d) = mi(line())
f = []
for _ in range(n):
	f.append(lmi(line()))
main(n, d, f)


(n, d) = list(map(int, input().split()))
li = []
for i in range(n):
	(m, s) = list(map(int, input().split()))
	li.append([m, s])
li.sort()
r = 0
c = 0
j = 0
for i in li:
	c += i[1]
	while i[0] - li[j][0] >= d:
		c -= li[j][1]
		j += 1
	r = max(r, c)
print(r)


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
from collections import Counter
(n, d) = map(int, input().split())
ans = 0
ls = []
for i in range(n):
	(m, f) = map(int, input().split())
	ls.append((m, f))
ls.sort()
ptr = 0
s = 0
for i in range(n):
	s += ls[i][1]
	while ptr < n and ls[i][0] - ls[ptr][0] >= d:
		s -= ls[ptr][1]
		ptr += 1
	ans = max(ans, s)
print(ans)


(n, d) = map(int, input().split())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
a.sort()
x = 0
y = 0
m = 0
f = 0
while y < n:
	if abs(a[y][0] - a[x][0]) < d:
		m += a[y][1]
		y += 1
		f = max(m, f)
	else:
		m -= a[x][1]
		x += 1
print(f)


(n, d) = map(int, input().split())
l = []
for i in range(n):
	(m, s) = map(int, input().split())
	l.append((m, s))
l.sort()
r = []
j = 0
s = 0
d1 = l[0][0]
for i in range(n):
	if l[i][0] - d1 < d:
		s += l[i][1]
	else:
		r.append(s)
		for k in range(j, i):
			if l[i][0] - l[k][0] >= d:
				s -= l[k][1]
				d1 = l[k + 1][0]
				j = k + 1
		s += l[i][1]
r.append(s)
print(max(r))


MOD = 1000000007
MOD2 = 998244353
ii = lambda : int(input())
si = lambda : input()
dgl = lambda : list(map(int, input()))
f = lambda : map(int, input().split())
il = lambda : list(map(int, input().split()))
ls = lambda : list(input())
(n, d) = f()
l = [list(f()) for _ in range(n)]
l.sort()
mx = 0
sm = 0
j = 0
for i in range(n):
	while j < n and l[j][0] - l[i][0] < d:
		sm += l[j][1]
		j += 1
	mx = max(mx, sm)
	sm -= l[i][1]
print(mx)


import collections as cc
import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(n, k) = I()
a = [I() for i in range(n)]
a.sort()
temp = 0
j = 0
ans = 0
for i in range(n):
	while a[i][0] - a[j][0] >= k:
		temp -= a[j][1]
		j += 1
	temp += a[i][1]
	ans = max(ans, temp)
print(ans)


(n, d) = [int(i) for i in input().split()]
frendo = [[0, 0]]
for i in range(n):
	xs = [int(x) for x in input().split()][:2]
	frendo.append(xs)

def cmp(xs):
	return xs[0]
frendo.sort(key=cmp)
j = 0
suma = rez = 0
diff = 0
for i in range(1, n + 1):
	suma += frendo[i][1]
	frendo[i][1] = suma
for i in range(n + 1):
	diff = frendo[i][0] - frendo[j][0]
	if diff < d:
		rez = max(rez, frendo[i][1] - frendo[j][1])
	else:
		while diff >= d:
			j += 1
			diff = frendo[i][0] - frendo[j][0]
		j -= 1
		rez = max(rez, frendo[i][1] - frendo[j][1])
print(rez)


def binary_search(arr, n, key):
	(l, r) = (0, n - 1)
	while l <= r:
		mid = l + r >> 1
		if arr[mid][0] <= key:
			l = mid + 1
		else:
			r = mid - 1
	return l

def main():
	(n, d) = map(int, input().split())
	arr = []
	for _ in range(n):
		(m, s) = map(int, input().split())
		arr += [(m, s)]
	arr.sort()
	arr_acc = [0] * (n + 1)
	for i in range(n):
		arr_acc[i + 1] = arr_acc[i] + arr[i][1]
	res = 0
	for i in range(n):
		key = arr[i][0] + d - 1
		j = binary_search(arr, n, key)
		res = max(res, arr_acc[j] - arr_acc[i])
	print(res)
main()


import sys

def binsearch(friends, start, end, d):
	low = start
	mid = 0
	high = end
	cost = 0
	flag = 0
	while low <= high:
		mid = (low + high) // 2
		if friends[mid][0] - friends[start][0] >= d:
			high = mid - 1
		elif mid == end or friends[mid + 1][0] - friends[start][0] >= d:
			break
		else:
			low = mid + 1
	if mid == end:
		flag = 1
	return (mid, flag)
(no_of_friends, difference) = [int(x) for x in input().split()]
friends = []
for i in range(0, no_of_friends):
	friend = tuple([int(x) for x in input().split()])
	friends.append(friend)
friends.sort(key=lambda x: x[0])
high = len(friends)
cost = -sys.maxsize
prefix = [0 for x in range(0, high + 1)]
prefix[1] = friends[0][1]
for i in range(2, high + 1):
	prefix[i] = prefix[i - 1] + friends[i - 1][1]
for i in range(0, no_of_friends):
	(end, flag) = binsearch(friends, i, high - 1, difference)
	tempcost = prefix[end + 1] - prefix[i]
	if tempcost > cost:
		cost = tempcost
	if flag == 1:
		break
print(cost)


(n, d) = [int(x) for x in input().split()]
prieteni = []
for i in range(n):
	pr = [int(x) for x in input().split()]
	prieteni += [pr]
prieteni.sort(key=lambda x: x[0])
l = 0
r = 0
final = prieteni[l][1]
max = 0
while r < n:
	if l == r:
		final = prieteni[l][1]
		r += 1
		if r == n:
			if final > max:
				max = final
			break
	if prieteni[r][0] - prieteni[l][0] < d:
		final += prieteni[r][1]
		r += 1
		if r == n:
			if final > max:
				max = final
	else:
		if final > max:
			max = final
		l += 1
		final = final - prieteni[l - 1][1]
print(max)


import math
s = input().split()
(n, d) = (int(s[0]), int(s[1]))
ms = []
for _ in range(n):
	st = input().split()
	if int(st[1]):
		ms.append((int(st[0]), int(st[1])))
ms = sorted(ms, key=lambda i: i[0])
(m, s) = ([], [])
for i in ms:
	m.append(i[0])
	s.append(i[1])
ssums = [0]
for i in s:
	ssums.append(ssums[-1] + i)
maxsSum = 0
iOverMaxEl = 1
for iMinEl in range(len(m)):
	if iOverMaxEl <= iMinEl:
		iOverMaxEl = iMinEl + 1
	while iOverMaxEl < len(s) and m[iOverMaxEl] - m[iMinEl] < d:
		iOverMaxEl += 1
	sSum = ssums[iOverMaxEl] - ssums[iMinEl]
	if sSum > maxsSum:
		maxsSum = sSum
print(maxsSum)


from collections import deque as dq
(a, b) = map(int, input().split())
v = []
for i in range(a):
	l = list(map(int, input().split()))
	v.append(l)
v.sort(key=lambda i: (i[0], i[1]), reverse=True)
t = p = dq([])
ans = out = 0
for i in v:
	if t == []:
		t.append(i[0])
		p.append(i[1])
		ans += i[1]
	else:
		while t and t[0] - i[0] >= b:
			k = t.popleft()
			ans -= p.popleft()
		t.append(i[0])
		p.append(i[1])
		ans += i[1]
	out = max(ans, out)
print(out)


(n, d) = map(int, input().split())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
a.sort(key=lambda x: x[0])
j = 0
friendship = 0
max_friendship = 0
for i in range(n):
	friendship += a[i][1]
	while a[j][0] + d <= a[i][0]:
		friendship -= a[j][1]
		j += 1
	max_friendship = max(friendship, max_friendship)
print(max_friendship)


(num_friends, poor) = [int(i) for i in input().split()]
party = []
for x in range(num_friends):
	temp_array = [0, 0]
	(temp_array[0], temp_array[1]) = [int(y) for y in input().split()]
	party.append(temp_array)
party.sort()
answer = party[0][1]
if len(party) == 1:
	print(answer)
	exit()
y = 0
temp_answer = 0
for x in range(0, len(party)):
	while y < len(party):
		if party[y][0] - party[x][0] < poor:
			temp_answer += party[y][1]
		else:
			if temp_answer > answer:
				answer = temp_answer
			temp_answer -= party[x][1]
			break
		y += 1
	if temp_answer > answer:
		answer = temp_answer
print(answer)


(n, d) = map(int, input().split())
v = []
for i in range(0, n):
	(a, b) = map(int, input().split())
	v.append((a, b))
v = sorted(v)
lo = 0
totalFriendship = v[0][1]
bestFriendship = totalFriendship
for i in range(1, n):
	while v[i][0] - v[lo][0] >= d:
		totalFriendship -= v[lo][1]
		lo += 1
	totalFriendship += v[i][1]
	bestFriendship = max(bestFriendship, totalFriendship)
print(bestFriendship)


(n, k) = map(int, input().split())
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
l.sort()
su = l[0][1]
ma = 0
(first, last) = (0, 1)
while first < n and last < n:
	if l[last][0] - l[first][0] >= k:
		if su > ma:
			ma = su
		su -= l[first][1]
		first += 1
	else:
		su += l[last][1]
		last += 1
if su > ma:
	ma = su
print(ma)


(n, money) = [int(x) for x in input().split()]
data = []
for i in range(n):
	d = [int(x) for x in input().split()]
	data.append(d)
data.sort(key=lambda x: x[0])
(i, j, soma, soma_parcial) = (0, 1, data[0][1], data[0][1])
while j < n and i < n:
	if abs(data[i][0] - data[j][0]) < money:
		soma_parcial += data[j][1]
		j += 1
	else:
		soma_parcial -= data[i][1]
		i += 1
	if soma_parcial > soma:
		soma = soma_parcial
print(soma)


I = lambda : map(int, input().split())
(n, d) = I()
a = sorted([list(I()) for i in range(n)])
s = ans = a[0][1]
j = 0
for i in range(1, n):
	while a[i][0] - a[j][0] >= d:
		s -= a[j][1]
		j += 1
	s += a[i][1]
	ans = max(s, ans)
print(ans)


(n, k) = [int(i) for i in input().split()]
arr = []
for i in range(n):
	s = [int(i) for i in input().split()]
	arr.append(s)
lst = []
arr.sort()
v = arr[0][1]
j = 1
for i in range(len(arr)):
	if j == n:
		break
	while abs(arr[i][0] - arr[j][0]) < k:
		v += arr[j][1]
		j += 1
		if j > n - 1:
			break
	lst.append(v)
	v -= arr[i][1]
lst = lst + [i[1] for i in arr]
print(max(lst))


(n, dr) = (int(i) for i in input().split())
a = []
for i in range(n):
	b = [int(i) for i in input().split()]
	a.append(b)
maxim = 0
s = 0
d = 0
hash = []
a.sort(key=lambda v: v[0])
hash.append(a[0])
d += 1
maxim = a[0][1]
actual = maxim
for i in a[1:]:
	while s < d:
		if i[0] - hash[s][0] < dr:
			break
		actual -= hash[s][1]
		s += 1
	d += 1
	hash.append(i)
	actual += i[1]
	maxim = max(maxim, actual)
print(maxim)


(n, diff) = map(int, input().split())
a = sorted([tuple(map(int, input().split())) for _ in range(n)])
left = right = 0
ret = 0
s = 0
while right < n:
	while right < n and a[right][0] - a[left][0] < diff:
		s += a[right][1]
		right += 1
	ret = max(ret, s)
	if right == n:
		break
	s += a[right][1]
	while left <= right and a[right][0] - a[left][0] >= diff:
		s -= a[left][1]
		left += 1
	right += 1
	ret = max(ret, s)
print(ret)


from collections import namedtuple
Friend = namedtuple('Friend', 'money value')
(n, d) = map(int, input().split())
a = []
for i in range(n):
	(money, value) = map(int, input().split())
	a.append(Friend(money, value))
a.sort()
s = ans = a[0].value
tail = 0
for head in range(1, n):
	while a[head].money - a[tail].money >= d:
		s -= a[tail].value
		tail += 1
	s += a[head].value
	ans = max(s, ans)
print(ans)


import sys
input = sys.stdin.readline

def check(num):
	(i, j) = (0, 0)
	count = 0
	while j < n:
		while j < n and a[j][0] - a[i][0] < d:
			count += a[j][1]
			j += 1
		if count >= num:
			return True
		count -= a[i][1]
		i += 1
	return False
(n, d) = map(int, input().split())
a = []
maxx = 0
for i in range(n):
	a.append(list(map(int, input().split())))
	maxx += a[-1][1]
a.sort()
if n == 1:
	print(a[0][1])
	exit()
low = 0
high = maxx
while low < high:
	mid = (low + high) // 2
	if check(mid):
		low = mid + 1
	else:
		high = mid - 1
if check(low):
	print(low)
else:
	print(low - 1)


def CMP(x):
	return x[0]

def b_search(l, r, x):
	ans = l
	while l <= r:
		mid = (l + r) // 2
		if a[mid][0] <= x:
			ans = mid
			l = mid + 1
		else:
			r = mid - 1
	return ans
s = input().split()
(n, d) = (int(s[0]), int(s[1]))
a = []
for i in range(n):
	s = input().split()
	a.append([int(s[0]), int(s[1])])
a.sort(key=CMP)
s = [0 for x in range(n)]
s[0] = a[0][1]
for i in range(1, n):
	s[i] = s[i - 1] + a[i][1]
ans = 0
for i in range(n):
	j = b_search(i, n - 1, a[i][0] + d - 1)
	if i == 0:
		ans = s[j]
	else:
		ans = max(ans, s[j] - s[i - 1])
print(ans)


(n, d) = [int(i) for i in input().split()]
lis = []
for i in range(n):
	(x, y) = [int(i) for i in input().split()]
	lis.append([x, y])
lis.sort()
pre_sum = [0] * n
pre_sum[0] = lis[0][1]
for i in range(1, n):
	pre_sum[i] = pre_sum[i - 1] + lis[i][1]
start = end = 0
ans = 0
while end < n:
	if lis[end][0] - lis[start][0] < d:
		if start == 0:
			ans = max(ans, pre_sum[end])
		else:
			ans = max(ans, pre_sum[end] - pre_sum[start - 1])
		end += 1
	else:
		start += 1
print(ans)


(n, d) = map(int, input().split())
a = []
for i in range(n):
	l = input().split()
	a.append(int(l[0]) * (10 ** 9 + 1) + int(l[1]))
a.sort()
b = []
c = []
x = a[0] % (10 ** 9 + 1)
y = a[0] // (10 ** 9 + 1)
b.append([y, x])
for i in range(1, n):
	x = a[i] % (10 ** 9 + 1)
	y = a[i] // (10 ** 9 + 1)
	b.append([y, x])
suma = 0
p1 = 0
p2 = 0
sol = 0
for p1 in range(n):
	while p2 < n and b[p2][0] - b[p1][0] < d:
		suma += b[p2][1]
		p2 += 1
	sol = max(sol, suma)
	suma -= b[p1][1]
print(sol)


(n, d) = map(int, input().split())
money = []
factor = []
for i in range(n):
	(m, s) = map(int, input().split())
	money.append(m)
	factor.append(s)
factor = [x for (_, x) in sorted(zip(money, factor))]
money = sorted(money)
i = j = 0
ans = 0
c = 0
while i < n and j < n:
	if money[j] - money[i] < d:
		c += factor[j]
		j += 1
	else:
		c -= factor[i]
		i += 1
	ans = max(c, ans)
print(ans)


(n, d) = map(int, input().split())
friend = [list(map(int, input().split())) for _ in range(n)]
friend.sort()
(i, j, ans, window) = (0, 0, 0, 0)
while i < n:
	if friend[i][0] - friend[j][0] < d:
		window += friend[i][1]
		ans = max(window, ans)
		i += 1
	else:
		window -= friend[j][1]
		j += 1
print(ans)


def sol(a, n, d):
	(i, j, ans, tmpans) = (0, 0, 0, 0)
	while j < n:
		if a[j][0] - a[i][0] < d:
			tmpans += a[j][1]
			j += 1
		else:
			ans = max(ans, tmpans)
			while a[j][0] - a[i][0] >= d:
				tmpans -= a[i][1]
				i += 1
	ans = max(ans, tmpans)
	return ans
(n, d) = map(int, input().split())
a = [None] * n
for i in range(n):
	a[i] = tuple(map(int, input().split()))
a.sort()
print(sol(a, n, d))


from sys import stdin, stdout
(n, d) = map(int, input().split())
l = []
for i in range(n):
	l.append(list(map(int, stdin.readline().split())))
l.sort()
from bisect import bisect_left
ans = 0
l1 = [0]
f = 0
for i in l:
	f += i[1]
	l1.append(f)
for i in range(1, n + 1):
	x = bisect_left(l, [l[i - 1][0] + d, 0])
	ans = max(ans, l1[x] - l1[i - 1])
print(ans)


line = input().split()
n = int(line[0])
d = int(line[1])
friends = []
for i in range(n):
	line = input().split()
	friends.append([int(line[0]), int(line[1])])
friends = sorted(friends, key=lambda x: x[0], reverse=True)
i = 0
frCoef = 0
max = 0
for j in range(len(friends)):
	frCoef += friends[j][1]
	while abs(friends[i][0] - friends[j][0]) >= d:
		frCoef -= friends[i][1]
		i += 1
	if frCoef > max:
		max = frCoef
print(max)


import bisect
(n, d) = map(int, input().split())
(a, b, c, i1, l, s, st, lt) = (0, 0, 0, 0, [], [], [], [])
f = 0
for (i, j) in enumerate(range(n)):
	(m, p) = map(int, input().split())
	l.append([m, p])
l = sorted(l, key=lambda li: li[0])
for (i, j) in enumerate(range(n)):
	s.append(l[i][0])
	st.append(l[i][1])
while i1 <= n - 1:
	a = bisect.bisect_right(s, s[i1] + (d - 1)) - 1
	c = bisect.bisect_left(s, s[a] - (d - 1))
	f = bisect.bisect_left(s, s[i1] - (d - 1))
	lt.append(sum(st[c:a + 1]))
	lt.append(sum(st[f:i1 + 1]))
	i1 = a + 1
print(max(lt))


import sys
input = sys.stdin.readline
read_tuple = lambda _type: map(_type, input().split(' '))
from math import factorial

def solve():
	(n, d) = read_tuple(int)
	friends = []
	for _ in range(n):
		(m, s) = read_tuple(int)
		friends.append((m, s))
	friends.sort(key=lambda x: x[0])
	(i, j, friendship, max_friendship) = (0, 0, 0, 0)
	while j < n:
		money_diff = friends[j][0] - friends[i][0]
		if money_diff < d:
			friendship += friends[j][1]
			max_friendship = max(max_friendship, friendship)
			j += 1
		else:
			friendship -= friends[i][1]
			i += 1
	print(max_friendship)
solve()


from operator import itemgetter
import time
(n, d) = [int(x) for x in input('').split()]
friends = []
for i in range(n):
	aux = [int(x) for x in input('').split()]
	friends.append((aux[0], aux[1]))
friends = sorted(friends, key=itemgetter(0))
primero = 0
segundo = 1

def cumple(a, b):
	return friends[b][0] - friends[a][0] < d
actual = friends[0][1]
maximo = friends[0][1]
while primero != len(friends) - 1:
	if cumple(primero, segundo):
		actual += friends[segundo][1]
		segundo += 1
		if maximo < actual:
			maximo = actual
	else:
		while not cumple(primero, segundo) and primero != segundo:
			actual -= friends[primero][1]
			primero += 1
		if primero == segundo:
			segundo += 1
			actual = friends[primero][1]
			if maximo < actual:
				maximo = actual
		if segundo == len(friends):
			segundo -= 1
	if segundo == len(friends):
		break
print(maximo)


(n, d) = map(int, input().split())
mon = []
pre = [0 for i in range(n)]
for i in range(n):
	(m, f) = map(int, input().split())
	mon.append((m, f))
mon.sort()
for i in range(n):
	(x, f) = mon[i]
	pre[i] = f
for i in range(1, n):
	pre[i] += pre[i - 1]
pre.append(0)
(j, i) = (0, 0)
ans = 0
su = 0
mx = 0
while i < n and j < n:
	(x, y) = mon[i]
	(res, res2) = mon[j]
	if res < x + d:
		j += 1
	else:
		mx = max(mx, pre[j - 1] - pre[i - 1])
		su = 0
		i += 1
mx = max(mx, pre[j - 1] - pre[i - 1])
print(mx)


(n, d) = [int(i) for i in input().split()]
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
a.sort()
j = 1
v = a[0][1]
maxx = []
for i in range(n):
	if j == n:
		break
	while abs(a[i][0] - a[j][0]) < d:
		v += a[j][1]
		j += 1
		if j > n - 1:
			break
	maxx.append(v)
	v -= a[i][1]
maxx = maxx + [i[1] for i in a]
print(max(maxx))


import sys
input = sys.stdin.readline
prnt = sys.stdout.write
(n, d) = map(int, input().split())
ls = []
for i in range(n):
	(m, f) = map(int, input().split())
	ls.append([m, f])
ls.sort()
mx = ls[0][1]
res = ls[0][1]
j = 0
for i in range(1, n):
	if ls[i][0] - ls[j][0] >= d:
		res = max(mx, res)
		while ls[i][0] - ls[j][0] >= d:
			j += 1
		mx = 0
		for x in range(j, i + 1):
			mx += ls[x][1]
	else:
		mx += ls[i][1]
res = max(mx, res)
prnt(str(res))


from functools import cmp_to_key

def readnums():
	return list(map(lambda x: int(x), input().split(' ')))

def mycmp(a, b):
	if a[0] > b[0]:
		return 1
	elif a[0] < b[0]:
		return -1
	else:
		if a[1] > b[1]:
			return 1
		elif a[1] < b[1]:
			return -1
		return 0
(n, d) = readnums()
fr = []
for i in range(n):
	fr.append(tuple(readnums()))
fr.sort(key=cmp_to_key(mycmp))
ans = 0
min_money = 0
friendship = 0
i = 0
j = 0
while i < n:
	min_money = fr[i][0]
	ans = max(ans, friendship)
	if i > j:
		j = i
	while j < n and abs(fr[j][0] - min_money) < d:
		friendship += fr[j][1]
		j += 1
		ans = max(ans, friendship)
	friendship -= fr[i][1]
	i += 1
print(ans)


import sys
input = sys.stdin.readline
read = lambda : map(int, input().split())
read_float = lambda : map(float, input().split())

def ceil(x):
	if x != int(x):
		x = int(x) + 1
	return x

def factorial(x, m):
	val = 1
	while x > 0:
		val = val * x % m
		x -= 1
	return val

def fact(x):
	val = 1
	while x > 0:
		val *= x
		x -= 1
	return val

def swaparr(arr, a, b):
	temp = arr[a]
	arr[a] = arr[b]
	arr[b] = temp

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

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

def nCr(n, k):
	if k > n:
		return 0
	if k > n - k:
		k = n - k
	res = 1
	for i in range(k):
		res = res * (n - i)
		res = res / (i + 1)
	return int(res)

def primefs(n):
	primes = {}
	while n % 2 == 0 and n > 0:
		primes[2] = primes.get(2, 0) + 1
		n = n // 2
	for i in range(3, int(n ** 0.5) + 2, 2):
		while n % i == 0 and n > 0:
			primes[i] = primes.get(i, 0) + 1
			n = n // i
	if n > 2:
		primes[n] = primes.get(n, 0) + 1
	return primes

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 swap(a, b):
	temp = a
	a = b
	b = temp
	return (a, b)

def find(x, link):
	p = x
	while p != link[p]:
		p = link[p]
	while x != p:
		nex = link[x]
		link[x] = p
		x = nex
	return p

def union(x, y, link, size):
	x = find(x, link)
	y = find(y, link)
	if size[x] < size[y]:
		(x, y) = swap(x, y)
	if x != y:
		size[x] += size[y]
		link[y] = x

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

def phi(n):
	result = n
	p = 2
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			result = result * (1.0 - 1.0 / float(p))
		p = p + 1
	if n > 1:
		result = result * (1.0 - 1.0 / float(n))
	return int(result)

def is_prime(n):
	if n == 0:
		return False
	if n == 1:
		return True
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True
MAXN = int(100000.0 + 5)

def spf_sieve():
	spf[1] = 1
	for i in range(2, MAXN):
		spf[i] = i
	for i in range(4, MAXN, 2):
		spf[i] = 2
	for i in range(3, ceil(MAXN ** 0.5), 2):
		if spf[i] == i:
			for j in range(i * i, MAXN, i):
				if spf[j] == j:
					spf[j] = i
spf = [0 for i in range(MAXN)]

def factoriazation(x):
	res = []
	for i in range(2, int(x ** 0.5) + 1):
		while x % i == 0:
			res.append(i)
			x //= i
	if x != 1:
		res.append(x)
	return res

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

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

def float_array():
	return list(map(float, input().strip().split()))

def str_array():
	return input().strip().split()

def binary_search(low, high, w, h, n):
	while low < high:
		mid = low + (high - low) // 2
		if check(mid, w, h, n):
			low = mid + 1
		else:
			high = mid
	return low

def check(div, n):
	if div == 0:
		return True
	return n % div == 0
MOD = int(1000000000.0) + 7
CMOD = 998244353
INF = float('inf')
NINF = -float('inf')
from itertools import permutations
import math
import bisect as bis
import random
import sys

def solve():
	(n, d) = read()
	friends = []
	for i in range(n):
		friends.append(list(read()))
	friends.sort()
	s = 0
	k = 0
	l = []
	r = []
	for x in friends:
		l.append(x[0])
		r.append(x[1])
	ps = [r[0]]
	for x in r:
		ps.append(ps[-1] + x)
	for i in range(n):
		j = bis.bisect_left(l, l[i] + d)
		s = max(ps[j] - ps[i], s)
	print(s)
for _ in range(1):
	solve()


from bisect import bisect
from itertools import accumulate

def intline():
	return [int(s) for s in input().split()]
(n, d) = intline()
friends = [intline() for i in range(n)]
friends.sort()
(money, friendship) = zip(*friends)
friendsums = [0] + list(accumulate(friendship))
optimal = []
for (i, m) in enumerate(money):
	optimal.append(friendsums[bisect(money, d + m - 1)] - friendsums[i])
print(max(optimal))


(n, d) = map(int, input().split())
arr = sorted((list(map(int, input().split())) for _ in range(n)))
(m, max_s, i) = (0, 0, 0)
for j in range(n):
	m += arr[j][1]
	while arr[j][0] - arr[i][0] >= d:
		m -= arr[i][1]
		i += 1
	max_s = max(max_s, m)
print(max_s)


from collections import defaultdict
(n, d) = map(int, input().split(' '))
friends = []
for i in range(n):
	(m, s) = map(int, input().split(' '))
	friends.append((m, s))
friends.sort()
friendship_factor = 0
(slow, fast) = (0, 0)
money_difference = 0
current_friendship = 0
while fast < n:
	current_friendship += friends[fast][1]
	while friends[fast][0] - friends[slow][0] >= d and slow < fast:
		current_friendship -= friends[slow][1]
		slow += 1
	friendship_factor = max(friendship_factor, current_friendship)
	fast += 1
print(friendship_factor)


l = input()
l = l.split()
n = int(l[0])
d = int(l[1])
lst = []
for i in range(n):
	l = input()
	l = l.split()
	lst.append((int(l[0]), int(l[1])))
lst.sort(key=lambda x: x[0])
(sum, maxim, start, fin) = (0, 0, 0, 0)
while fin < n:
	while fin < n and lst[fin][0] - lst[start][0] + 1 <= d:
		sum += lst[fin][1]
		fin += 1
	maxim = max(maxim, sum)
	sum -= lst[start][1]
	start += 1
print(maxim)


def byF(p1):
	(x, y) = p1
	return x
(n, d) = map(int, input().split())
friends = []
iSt = 0
s = 0
m = 0
for i in range(n):
	(x, y) = map(int, input().split())
	friends.append((x, y))
friends.sort(key=byF)
for i in range(n):
	s += friends[i][1]
	while friends[i][0] - friends[iSt][0] >= d:
		s -= friends[iSt][1]
		iSt += 1
	if s > m:
		m = s
print(m)


(n, d) = map(int, input().split())
l = []
for i in range(n):
	(x, y) = map(int, input().split())
	l.append([x, y])
l.sort()
i = 0
sm = 0
ans = 0
for j in range(n):
	sm += l[j][1]
	while l[j][0] - l[i][0] >= d:
		sm -= l[i][1]
		i += 1
	ans = max(ans, sm)
print(ans)


from collections import deque
(n, d) = map(int, input().split())
a = [list(map(int, input().split())) for i in range(n)]
a.sort()
q = deque()
ans = s = 0
for (x, f) in a:
	while q and x >= q[0][0] + d:
		s -= q[0][1]
		q.popleft()
	q.append((x, f))
	s += f
	ans = max(s, ans)
print(ans)


import math
(n, d) = map(int, input().split())
store = []
for _ in range(n):
	(money, ff) = map(int, input().split())
	store.append((money, ff))
store.sort()
ptr1 = 0
ptr2 = 0
MAX = 0
score = 0
while ptr1 < n or ptr2 < n:
	count = 0
	while ptr1 < n and ptr2 < n and (store[ptr1][0] - store[ptr2][0] < d):
		count += 1
		score += store[ptr1][1]
		MAX = max(MAX, score)
		ptr1 += 1
		if ptr1 == n:
			break
	while ptr1 < n and ptr2 < n and (store[ptr1][0] - store[ptr2][0] >= d):
		count += 1
		score -= store[ptr2][1]
		ptr2 += 1
		if ptr2 == n:
			break
	if count == 0:
		ptr1 += 1
		ptr2 += 1
print(MAX)


(n, d) = map(int, input().split())
friends = sorted([list(map(int, input().split())) for i in range(n)])
current = friends[0][1]
best = current
(left, right) = (0, 0)
while True:
	right += 1
	if right == n:
		break
	current += friends[right][1]
	while friends[right][0] - friends[left][0] >= d:
		current -= friends[left][1]
		left += 1
	best = max(best, current)
print(best)


(N, D) = map(int, input().split())
L = []
for i in range(N):
	(m, s) = map(int, input().split())
	L.append((m, s))
L.sort()
left = 0
right = 0
now = 0
ans = -1
while right < N:
	if L[right][0] - L[left][0] < D:
		now += L[right][1]
		ans = max(ans, now)
		right += 1
	else:
		now -= L[left][1]
		left += 1
print(ans)


(n, d) = map(int, input().split())
friends = []
for i in range(n):
	(m, f) = map(int, input().split())
	friends.append([m, f])
friends.sort(key=lambda x: x[0])
(l, r, s) = (0, 0, friends[0][1])
sums = []
for i in range(1, n):
	r += 1
	if friends[r][0] - friends[l][0] < d:
		s += friends[i][1]
	else:
		sums.append(s)
		while friends[r][0] - friends[l][0] >= d:
			s -= friends[l][1]
			l += 1
		s += friends[r][1]
sums.append(s)
print(max(sums))


(n, d) = map(int, input().split())
m_s = sorted((tuple(map(int, input().split())) for _ in range(n)))
(s, max_s, i) = (0, 0, 0)
for j in range(n):
	s += m_s[j][1]
	while m_s[j][0] - m_s[i][0] >= d:
		s -= m_s[i][1]
		i += 1
	max_s = max(max_s, s)
print(max_s)


(n, d) = map(int, input().split())
line = list()
for i in range(n):
	line.append(list(map(int, input().split())))
line.sort(key=lambda a: a[0])
refer = list()
note = line[0][0]
flag_a = flag_b = False
flag_v = 0
for i in range(n - 1):
	if flag_a:
		if flag_v - line[i][0] >= d:
			continue
		else:
			flag_a = False
	if flag_b:
		break
	for j in range(i + 1, n):
		if line[j][0] - line[i][0] >= d:
			refer.append(sum([line[k][1] for k in range(i, j)]))
			flag_a = True
			flag_v = line[j][0]
			break
		if j == n - 1:
			refer.append(sum([line[k][1] for k in range(i, n)]))
			flag_b = True
			break
refer.append(line[-1][1])
print(max(refer))


(n, d) = map(int, input().split())
friends = [tuple(map(int, input().split())) for i in range(n)]
friends = sorted(friends, key=lambda f: f[0])
sums = []
curr = 0
for i in range(n):
	curr += friends[i][1]
	sums.append(curr)
res = 0
for i in range(n):
	low = i
	high = n - 1
	curr = friends[i][0]
	while low < high:
		mid = (low + high + 1) // 2
		if abs(curr - friends[mid][0]) >= d:
			high = mid - 1
		else:
			low = mid
	res = max(res, sums[low] - (0 if i == 0 else sums[i - 1]))
print(res)


(n, d) = map(int, input().split())
friends = dict()
for _ in range(n):
	(k, v) = map(int, input().split())
	if k in friends:
		friends[k] += v
	else:
		friends[k] = v
ans = 0
tmp = i = j = 0
keys = sorted(friends.keys())
vals = [friends[k] for k in keys]
while j < len(keys):
	while j < len(keys) and keys[j] - keys[i] < d:
		tmp += vals[j]
		j += 1
	ans = max(ans, tmp)
	tmp -= vals[i]
	i += 1
print(ans)


class Guest(object):

	def __init__(self, money, friendship_factor):
		self.money = money
		self.friendship_factor = friendship_factor

	def __repr__(self):
		return 'Guest'

	def __str__(self):
		return ' '.join(['Guest:', str(self.money), str(self.friendship_factor)])

class Company(object):

	def __init__(self, number_of_guests, poorness_threshold):
		self.number_of_guests = number_of_guests
		self.poorness_threshold = poorness_threshold
		self.list_of_guests = list()
		self.maximum_sum_of_friendship = 0

	def add_guest(self, money, friendship_factor):
		self.list_of_guests.append(Guest(money, friendship_factor))

	def sort_guest_list(self):
		self.list_of_guests.sort(key=lambda guest: guest.money)

	def compute_maximal_friendship(self):
		temporary_friendship = 0
		trailing_guest_index = 0
		for guest_index in range(self.number_of_guests):
			temporary_friendship += self.list_of_guests[guest_index].friendship_factor
			while self.list_of_guests[guest_index].money - self.list_of_guests[trailing_guest_index].money >= self.poorness_threshold:
				temporary_friendship -= self.list_of_guests[trailing_guest_index].friendship_factor
				trailing_guest_index += 1
			if self.maximum_sum_of_friendship < temporary_friendship:
				self.maximum_sum_of_friendship = temporary_friendship
(input_number_of_guests, input_poorness_threshold) = map(int, input().split(' '))
company = Company(input_number_of_guests, input_poorness_threshold)
for counter in range(input_number_of_guests):
	(input_money, input_friendship_factor) = map(int, input().split(' '))
	company.add_guest(input_money, input_friendship_factor)
company.sort_guest_list()
company.compute_maximal_friendship()
print(company.maximum_sum_of_friendship)


(n, d) = [int(i) for i in input().split(' ')]
friends = [[int(i) for i in input().split(' ')] for _ in range(n)]
friends.sort(key=lambda x: x[0])
first = 0
last = 0
max_friendship = 0
friendship = 0
while last < n:
	while first <= last and friends[last][0] - friends[first][0] >= d:
		friendship -= friends[first][1]
		first += 1
	friendship += friends[last][1]
	max_friendship = max(max_friendship, friendship)
	last += 1
print(max_friendship)


(n, de) = map(int, input().split())
d = {}
for i in range(n):
	(m, f) = map(int, input().split())
	d[m] = f if m not in d else d[m] + f
l = list(d.keys())
l.sort()
a = 0
maxf = 0
curf = 0
for b in range(len(l)):
	if l[b] >= de + l[a]:
		while 1:
			if l[b] - l[a] < de:
				break
			else:
				curf -= d[l[a]]
				a += 1
	curf += d[l[b]]
	maxf = max(maxf, curf)
print(maxf)


(n, d) = [int(i) for i in input().split()]
friends = [[0, 0] for i in range(n)]
for i in range(n):
	a = input().split()
	friends[i][0] = int(a[0])
	friends[i][1] = int(a[1])
friends.sort()
l = 0
r = 0
result = 0
add = 0
while l < n and r < n:
	while r < n and friends[r][0] - friends[l][0] < d:
		add += friends[r][1]
		r += 1
	result = max(result, add)
	add -= friends[l][1]
	l += 1
print(result)


def lb(l, r, a, k):
	while l < r:
		m = (l + r) // 2
		if a[m] < k:
			l = m + 1
		else:
			r = m
	return l

def ub(l, r, a, k):
	while l < r:
		m = (l + r) // 2
		if a[m] <= k:
			l = m + 1
		else:
			r = m
	return l

def part(a, b, v):
	if a - 1 < 0:
		return v[b][1]
	return v[b][1] - v[a - 1][1]
(n, m) = input().split()
arr = list()
ll = list()
for i in range(int(n)):
	(a, b) = input().split()
	arr.append((int(a), int(b)))
	ll.append(int(a))
arr.sort()
ll.sort()
for i in range(1, len(arr)):
	arr[i] = (arr[i][0], arr[i][1] + arr[i - 1][1])
rpta = 0
cnt = 0
for i in ll:
	f = lb(0, int(n), ll, i - int(m) + 1)
	rpta = max(rpta, part(f, cnt, arr))
	cnt = cnt + 1
print(rpta)


(n, d) = map(int, input().split())
li = []
for i in range(n):
	li.append(list(map(int, input().split())))
li = sorted(li)
su = [0] * n
su[0] = li[0][1]
for i in range(1, n):
	su[i] = su[i - 1] + li[i][1]
li = [x[0] for x in li]
po = 0
ma = 0
for i in range(n):
	while po < n - 1 and li[po + 1] - li[i] < d:
		po = po + 1
	if i == 0:
		ma = max(ma, su[po])
	else:
		ma = max(ma, su[po] - su[i - 1])
print(ma)


def cmp(a):
	return a[0]
(n, d) = [int(x) for x in input().split()]
arr = []
for i in range(n):
	l = [int(x) for x in input().split()]
	arr.append(l)
arr.sort(key=cmp)
i = 0
ans = arr[0][1]
now = arr[0][1]
for j in range(1, n):
	if arr[j][0] - arr[i][0] < d:
		now += arr[j][1]
	else:
		if now > ans:
			ans = now
		while arr[j][0] - arr[i][0] >= d:
			now -= arr[i][1]
			i += 1
		now += arr[j][1]
if now > ans:
	ans = now
print(ans)


import unittest
import sys

class Company:

	def __init__(self, test_inputs=None):
		it = iter(test_inputs.split('\n')) if test_inputs else None

		def uinput():
			return next(it) if it else sys.stdin.readline().rstrip()
		[self.n, self.d] = list(map(int, uinput().split()))
		pairs = ' '.join((uinput() for i in range(self.n))).split()
		self.numa = [int(pairs[i]) for i in range(0, 2 * self.n, 2)]
		self.numb = [int(pairs[i]) for i in range(1, 2 * self.n, 2)]
		self.money = [(self.numa[i], self.numb[i]) for i in range(self.n)]
		self.money = sorted(self.money)
		self.partsum = [0]
		sum = 0
		for i in range(self.n):
			sum += self.money[i][1]
			self.partsum.append(sum)

	def calculate(self):
		result = 0
		for i in range(self.n):
			mlb = self.money[i][0]
			mrb = mlb + self.d
			ilb = i
			irb = lbound(self.money, mrb)
			sumf = self.partsum[irb] - self.partsum[ilb]
			result = max(result, sumf)
		return str(result)

def lbound(v, n):
	b = 0
	e = len(v)
	while b != e:
		mid = (b + e) // 2
		if v[mid][0] < n:
			b = mid + 1
		else:
			e = mid
	return b

class unitTests(unittest.TestCase):

	def test_single_test(self):
		test = '4 5\n75 5\n0 100\n150 20\n75 1'
		d = Company(test)
		self.assertEqual(d.n, 4)
		self.assertEqual(d.d, 5)
		self.assertEqual(d.numa, [75, 0, 150, 75])
		self.assertEqual(d.numb, [5, 100, 20, 1])
		self.assertEqual(Company(test).calculate(), '100')
		test = '5 100\n0 7\n11 32\n99 10\n46 8\n87 54'
		self.assertEqual(Company(test).calculate(), '111')
		test = ''
		test = ''

	def time_limit_test(self, nmax):
		import random
		import timeit
		test = str(nmax) + ' ' + str(nmax) + '\n'
		numnums = [str(i) + ' ' + str(i + 1) for i in range(nmax)]
		test += '\n'.join(numnums) + '\n'
		nums = [random.randint(1, 10000) for i in range(nmax)]
		test += ' '.join(map(str, nums)) + '\n'
		start = timeit.default_timer()
		d = Company(test)
		calc = timeit.default_timer()
		d.calculate()
		stop = timeit.default_timer()
		print('\nTimelimit Test: ' + '{0:.3f}s (init {1:.3f}s calc {2:.3f}s)'.format(stop - start, calc - start, stop - calc))

def __starting_point():
	sys.setrecursionlimit(100000)
	if sys.argv[-1] == '-ut':
		unittest.main(argv=[' '])
	sys.stdout.write(Company().calculate())
__starting_point()


def cmp(t):
	return t[0]
(n, d) = (int(i) for i in input().split())
lista = []
for i in range(n):
	(a, b) = (int(i) for i in input().split())
	lista.append((a, b))
lista.sort(key=cmp)
maxim = 0
j = 0
crt = 0
for i in range(len(lista)):
	while j < len(lista) and lista[j][0] - lista[i][0] < d:
		crt = crt + lista[j][1]
		j += 1
	if maxim < crt:
		maxim = crt
	crt = crt - lista[i][1]
print(maxim)


(n, d) = map(int, input().split())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
a.sort()
p1 = p2 = 0
ma = 0
su = 0
while p2 < n:
	if a[p2][0] - a[p1][0] < d:
		su += a[p2][1]
		p2 += 1
		ma = max(ma, su)
	else:
		su -= a[p1][1]
		p1 += 1
print(ma)


(n, d) = map(int, input().split())
di = []
for _ in range(n):
	(m, f) = map(int, input().split())
	di.append([m, f])
di.sort(key=lambda x: x[0])
i = j = 0
ans = 0
s = 0
while j < n:
	if di[j][0] - di[i][0] < d:
		s += di[j][1]
		j += 1
		ans = max(ans, s)
	else:
		s -= di[i][1]
		i += 1
print(ans)


(n, d) = map(int, input().split())
l = sorted((list(map(int, input().split())) for _ in range(n)))
j = 0
fl = 0
m = 0
for i in range(n):
	fl += l[i][1]
	while l[i][0] - l[j][0] >= d:
		fl -= l[j][1]
		j += 1
	m = max(m, fl)
print(m)


(n, d) = map(int, input().split())
l = []
for i in range(n):
	(x, y) = map(int, input().split())
	l.append((x, y))
l.sort()
v = []
f = []
for (i, j) in l:
	v.append(i)
	f.append(j)
count = f[0]
max_count = f[0]
i = 0
j = 1
while j < n:
	max_count = max(count, max_count)
	if v[j] - v[i] < d:
		count += f[j]
		j += 1
	else:
		count -= f[i]
		i += 1
	max_count = max(count, max_count)
print(max_count)


import re
import sys
exit = sys.exit
from bisect import bisect_left as bsl, bisect_right as bsr
from collections import Counter, defaultdict as ddict, deque
from functools import lru_cache
cache = lru_cache(None)
from heapq import *
from itertools import *
from math import inf
from pprint import pprint as pp
enum = enumerate
ri = lambda : int(rln())
ris = lambda : list(map(int, rfs()))
rln = sys.stdin.readline
rl = lambda : rln().rstrip('\n')
rfs = lambda : rln().split()
mod = 1000000007
d4 = [(0, -1), (1, 0), (0, 1), (-1, 0)]
d8 = [(-1, -1), (0, -1), (1, -1), (-1, 0), (1, 0), (-1, 1), (0, 1), (1, 1)]
(n, d) = ris()
a = []
for _ in range(n):
	a.append(ris())
a.sort()
ans = s = l = 0
for r in range(n):
	s += a[r][1]
	while d <= a[r][0] - a[l][0]:
		s -= a[l][1]
		l += 1
	ans = max(ans, s)
print(ans)


import sys
input = lambda : sys.stdin.readline().strip('\r\n')
(n, d) = map(int, input().split())
ls = []
for _ in range(n):
	(m, s) = map(int, input().split())
	ls.append((m, s))
ls.sort()
alpha = 0
maxi = 0
j = 0
for i in range(n):
	alpha += ls[i][1]
	while ls[i][0] - ls[j][0] >= d:
		alpha -= ls[j][1]
		j += 1
	maxi = max(maxi, alpha)
print(maxi)


(n, d) = map(int, input().split())
m = [0 for i in range(n)]
s = [0 for i in range(n)]
hash = [0 for i in range(n)]
mod = 10 ** 9 + 1
for i in range(n):
	(m[i], s[i]) = map(int, input().split())
	hash[i] = m[i] * mod + s[i]
hash = sorted(hash)

def get_value(x):
	return x % mod

def get_key(x):
	return int(x / mod)
i_max = n - 1
i_min = n - 1
S = 0
S_max = S
while (i_min >= 0) & (i_max >= 0):
	while (get_key(hash[i_min]) > get_key(hash[i_max]) - d) & (i_min >= 0):
		S += get_value(hash[i_min])
		i_min -= 1
	if S > S_max:
		S_max = S
	S -= get_value(hash[i_max])
	i_max -= 1
print(S_max)


(n, d) = map(int, input().split())
arr = []
for i in range(n):
	arr.append(list(map(int, input().split())))
arr.sort(key=lambda arr: arr[0])
maxx = 0
left = 0
right = 0
curr = 0
while right < n and left < n:
	if abs(arr[left][0] - arr[right][0]) < d:
		curr += arr[right][1]
		right += 1
	else:
		curr -= arr[left][1]
		left += 1
	maxx = max(curr, maxx)
print(maxx)


def sortam(t):
	return t[0]

def sortamPrim(t):
	return t[1]
s = input().split()
n = int(s[0])
d = int(s[1])
bani_prietenie = []
for i in range(n):
	s = input().split()
	bani_prietenie.append((int(s[0]), int(s[1])))
bani_prietenie.sort(key=sortamPrim)
bani_prietenie.sort(key=sortam)
st = 0
dr = -1
s = 0
maximum = 0
while st < n:
	while dr + 1 < n and bani_prietenie[dr + 1][0] - bani_prietenie[st][0] < d:
		dr += 1
		s += bani_prietenie[dr][1]
	maximum = max(maximum, s)
	s -= bani_prietenie[st][1]
	st += 1
print(maximum)


import sys
from functools import lru_cache, cmp_to_key
from heapq import merge, heapify, heappop, heappush, nlargest, nsmallest
from math import ceil, floor, gcd, fabs, factorial, fmod, sqrt, inf, log
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
mod = pow(10, 9) + 7
mod2 = 998244353

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

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

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

def sl():
	return list(ssp())

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

def cmp(a, b):
	if a[0] < b[0]:
		return -1
	if a[0] > b[0]:
		return 1
	if a[1] > b[1]:
		return -1
	return 1
(n, d) = sp()
mat = []
for i in range(n):
	mat.append(l())
mat = sorted(mat, key=cmp_to_key(cmp))
(money, factor) = ([i[0] for i in mat], [i[1] for i in mat])
pref = dd(int)
pref[0] = factor[0]
for i in range(1, n):
	pref[i] = pref[i - 1] + factor[i]
answer = 0
for i in range(n):
	res = factor[i]
	temp = bl(money, money[i] + d)
	if temp == n:
		temp -= 1
	while money[temp] >= money[i] + d:
		temp -= 1
	res += pref[temp] - pref[i]
	answer = max(answer, res)
out(answer)


from sys import stdin

def solve(people, d):
	ls = sorted(people, key=lambda p: p[0])
	ans = ls[0][1]
	acc = 0
	last = -1
	for (idx, (m, s)) in enumerate(ls):
		while last >= 0 and idx - last > 0 and (m - ls[last][0] >= d):
			acc -= ls[last][1]
			last += 1
		acc += s
		if last < 0 or idx - last <= 0:
			last = idx
		ans = max(ans, acc)
	return ans
(n, d) = tuple(map(int, input().split()))
friends = [tuple(map(int, line.split())) for line in stdin.readlines()]
ans = solve(friends, d)
print(ans)


(n, d) = [int(i) for i in input().split()]
friends = []
for i in range(n):
	lista = []
	(m, s) = [int(i) for i in input().split()]
	lista = [m, s]
	friends.append(lista)
friends_ordenados = sorted(friends)
soma_factors = []
(inicio, fim, soma) = (0, 0, 0)
while fim < n:
	if friends_ordenados[fim][0] - friends_ordenados[inicio][0] < d:
		soma += friends_ordenados[fim][1]
		fim += 1
	else:
		soma_factors.append(soma)
		soma -= friends_ordenados[inicio][1]
		inicio += 1
soma_factors.append(soma)
print(max(soma_factors))


(n, d) = map(int, input().split())
friends = [[0, 0]]
for i in range(n):
	(m, f) = map(int, input().split())
	friends.append([m, f])
friends.sort()
friendship = [0]
monies = []
for i in range(1, n + 1):
	friendship.append(friendship[i - 1] + friends[i][1])
ans = 0
j = 0
diff = 0
for i in range(n + 1):
	diff = friends[i][0] - friends[j][0]
	if diff < d:
		ans = max(friendship[i] - friendship[j], ans)
	else:
		while diff >= d:
			j += 1
			diff = friends[i][0] - friends[j][0]
		j -= 1
		ans = max(ans, friendship[i] - friendship[j])
print(ans)


(n, d) = map(int, input().split())
vals = []
for i in range(n):
	(m, s) = map(int, input().split())
	vals.append((m, s))
vals.sort()
maxVal = vals[0][1]
position = 1
totals = vals[0][1]
for (m, s) in vals:
	while position < len(vals) and vals[position][0] < m + d:
		totals += vals[position][1]
		position += 1
	if totals > maxVal:
		maxVal = totals
	totals -= s
print(maxVal)


(n, d) = map(int, input().split())
al = [list(map(int, input().split())) for _ in range(n)]
al.sort()
res = al[0][1]
t = al[0][1]
idx = 0
for i in range(1, n):
	if al[i][0] - al[idx][0] < d:
		t += al[i][1]
	else:
		while al[i][0] - al[idx][0] >= d:
			t -= al[idx][1]
			idx += 1
		t += al[i][1]
	res = max(res, t)
print(res)


from sys import stdin, stdout
from math import gcd, ceil, sqrt
ii1 = lambda : int(stdin.readline().strip())
is1 = lambda : stdin.readline().strip()
iia = lambda : list(map(int, stdin.readline().strip().split()))
isa = lambda : stdin.readline().strip().split()
mod = 1000000007
(n, d) = iia()
frds = []
for _ in range(n):
	frds.append(iia())
frds.sort()
res = float('-inf')
tot = frds[0][1]
p = 0
for i in range(1, n):
	while frds[i][0] - frds[p][0] >= d:
		res = max(res, tot)
		tot -= frds[p][1]
		p += 1
	tot += frds[i][1]
res = max(res, tot)
print(res)


def getKey(item):
	return item[0]
(n, d) = map(int, input().split())
li = []
for _ in range(n):
	l = [int(x) for x in input().split()]
	li.append(l)
li = sorted(li, key=getKey)
mx = -1
sum = [0] * n
sum[0] = li[0][1]
for i in range(1, n):
	sum[i] = sum[i - 1] + li[i][1]
end = 0
for i in range(0, n):
	tmp = end
	for j in range(tmp, n):
		if li[j][0] - li[i][0] < d:
			end = j
		else:
			break
	cnt = li[i][1]
	if end > i and i == 0:
		cnt = sum[end]
	elif end > i:
		cnt = sum[end] - sum[i - 1]
	if cnt > mx:
		mx = cnt
print(mx)


(n, d) = [int(i) for i in input().split()]
dr = []
for i in range(n):
	dr.append([int(i) for i in input().split()])
dr.sort()
fri = []
l = 0
r = 1
fr = 0
go = dr[0][1]
for l in range(n):
	fr = dr[l][0]
	while r < n and dr[r][0] - fr < d:
		go += dr[r][1]
		r += 1
	fri.append(go)
	go -= dr[l][1]
print(max(fri))


import sys
ii = lambda : sys.stdin.readline().strip()
idata = lambda : [int(x) for x in ii().split()]
(n, d) = idata()
sp = []
for i in range(n):
	sp += [idata()]
sp.sort()
(l, r, maxx, ans) = (0, 0, sp[0][1], sp[0][1])
while r != n - 1:
	r += 1
	maxx += sp[r][1]
	while sp[r][0] - sp[l][0] >= d:
		maxx -= sp[l][1]
		l += 1
	ans = max(ans, maxx)
print(ans)


(n, d) = map(int, input().split())
a = []
import sys
for i in range(n):
	x = list(map(int, sys.stdin.readline().split()))
	a.append(x)
a.sort()
i = 0
mx = 0
x = a[i][0]
s = a[i][1]
j = 1
while j != n:
	if a[j][0] - x < d:
		s += a[j][1]
		mx = max(s, mx)
		j += 1
	else:
		mx = max(s, mx)
		s -= a[i][1]
		i += 1
		x = a[i][0]
print(max(mx, s))


(n, d) = [int(x) for x in input().split()]
from collections import defaultdict
m = defaultdict(int)
s = defaultdict(int)
for i in range(n):
	(m[i], s[i]) = [int(x) for x in input().split()]
mmm = [m[x] for x in sorted(m, key=m.__getitem__)]
sss = [s[x] for x in sorted(m, key=m.__getitem__)]
(a, b) = (0, 0)
mx = 0
ss = sss[0]
while b < n:
	dif = mmm[b] - mmm[a]
	if dif >= d:
		ss -= sss[a]
		a += 1
	elif dif < d:
		mx = ss if ss > mx else mx
		b += 1
		if b < n:
			ss += sss[b]
	else:
		pass
print(mx)


entrada = list(map(int, input().split(' ')))
lista = []
friendship = 0
p = 1
for i in range(entrada[0]):
	temp = list(map(int, input().split()))
	lista.append((temp[0], temp[1]))
lista.sort()
lista2 = [0]
for i in range(1, entrada[0] + 1):
	lista2.append(lista2[i - 1] + lista[i - 1][1])
for i in range(entrada[0]):
	while p < entrada[0] and lista[i][0] + entrada[1] > lista[p][0]:
		p += 1
	friendship = max(friendship, lista2[p] - lista2[i])
print(friendship)


friends = []
(n, d) = map(int, input().split())
for i in range(n):
	friends.append(tuple(map(int, input().split())))
friends.sort()
sums = [friends[0][1]]
for i in range(1, n):
	sums.append(sums[i - 1] + friends[i][1])
l = r = 0
answer = 0
while l <= n - 1 and r <= n - 1:
	if friends[r][0] - friends[l][0] < d:
		if sums[r] - sums[l] + friends[l][1] > answer:
			answer = sums[r] - sums[l] + friends[l][1]
		r += 1
	elif l <= r - 1:
		l += 1
	else:
		r += 1
print(answer)


debug = lambda *args: args

def search(lo, hi, frds, t):
	while lo < hi:
		mid = lo + int((hi - lo + 1) / 2)
		if frds[mid][0] <= t:
			lo = mid
		else:
			hi = mid - 1
	return lo
(n, d) = [int(x) for x in input().split(' ')]
frds = []
z = {}
for i in range(n):
	p = [int(x) for x in input().split(' ')]
	debug(i, p, n)
	if p[0] in z:
		z[p[0]][1] += p[1]
		debug('\t', p)
	else:
		z[p[0]] = p
		frds.append(p)
frds = sorted(frds)
debug(frds)
scores = [0]
for f in frds:
	scores.append(scores[-1] + f[1])
debug(scores)
c = 0
q = 0
ans = 0
for f in frds:
	c += scores[q]
	debug(frds[0][0] + d - 1)
	idx = search(q, len(frds) - 1, frds, f[0] + d - 1)
	sum = scores[idx + 1] - scores[q]
	debug(f, q, idx + 1, sum, '\t\t', q, len(frds) - 1)
	if sum > ans:
		debug('\t', q, ans, idx + 1, sum)
		ans = sum
	q += 1
print(ans)


(n, d) = [int(x) for x in input().split()]
friends = []
for _n in range(n):
	friends.append([int(x) for x in input().split()])
friends.sort(key=lambda x: x[0])
maxFriend = 0
curFriend = 0
start = 0
end = 0
while start < len(friends) and end < len(friends):
	if friends[end][0] - friends[start][0] >= d:
		curFriend -= friends[start][1]
		start += 1
	else:
		curFriend += friends[end][1]
		end += 1
		maxFriend = max(maxFriend, curFriend)
print(maxFriend)


def main():

	def solve(arr):
		arr.sort(key=lambda x: x[0])
		l = 0
		s = 0
		max_ = 0
		for i in range(len(arr)):
			s += arr[i][1]
			while arr[i][0] - arr[l][0] >= d:
				s -= arr[l][1]
				l += 1
			max_ = max(max_, s)
		return max_
	q = []
	(n, d) = list(map(lambda x: int(x), input().split()))
	for i in range(n):
		(money, ff) = list(map(lambda x: int(x), input().split()))
		q.append((money, ff))
	print(solve(q))
py2 = round(0.5)
if py2:
	from future_builtins import ascii, filter, hex, map, oct, zip
	range = xrange
import os, sys
from io import IOBase, BytesIO
BUFSIZE = 8192

class FastIO(BytesIO):
	newlines = 0

	def __init__(self, file):
		self._file = file
		self._fd = file.fileno()
		self.writable = 'x' in file.mode or 'w' in file.mode
		self.write = super(FastIO, self).write if self.writable else None

	def _fill(self):
		s = os.read(self._fd, max(os.fstat(self._fd).st_size, BUFSIZE))
		self.seek((self.tell(), self.seek(0, 2), super(FastIO, self).write(s))[0])
		return s

	def read(self):
		while self._fill():
			pass
		return super(FastIO, self).read()

	def readline(self):
		while self.newlines == 0:
			s = self._fill()
			self.newlines = s.count(b'\n') + (not s)
		self.newlines -= 1
		return super(FastIO, self).readline()

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		if py2:
			self.write = self.buffer.write
			self.read = self.buffer.read
			self.readline = self.buffer.readline
		else:
			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 types import GeneratorType

def bootstrap(func, stack=[]):

	def wrapped_function(*args, **kwargs):
		if stack:
			return func(*args, **kwargs)
		else:
			call = func(*args, **kwargs)
			while True:
				if type(call) is GeneratorType:
					stack.append(call)
					call = next(call)
				else:
					stack.pop()
					if not stack:
						break
					call = stack[-1].send(call)
			return call
	return wrapped_function
main()


(n, d) = tuple(map(int, input().split()))
(m, s) = ([0] * n, [0] * n)
ms = [0] * n
for i in range(n):
	(m[i], s[i]) = tuple(map(int, input().split()))
	ms[i] = (m[i], s[i])
suffix = [0] * n
postfix = [0] * n
alsum = sum(s)
ms.sort()
for i in range(1, n):
	postfix[i] = postfix[i - 1] + ms[i - 1][1]
for i in range(n - 2, -1, -1):
	suffix[i] = suffix[i + 1] + ms[i + 1][1]
friends = []
for i in range(n):
	left = i - 1
	right = n - 1
	while right - left > 1:
		middle = (right + left) // 2
		if ms[middle][0] >= ms[i][0] + d:
			right = middle
		else:
			left = middle
	rich = right
	if ms[rich][0] >= ms[i][0] + d:
		rich -= 1
	friends.append(alsum - postfix[i] - suffix[rich])
print(max(friends))


(n, d) = map(int, input().split())
arr = []
xx = 0
for i in range(n):
	(m, fr) = map(int, input().split())
	xx += m
	arr.append([m, fr, xx])
arr = sorted(arr)
cc = 0
ans = 0
r = 0
for i in range(len(arr)):
	while r < len(arr) and arr[r][0] - arr[i][0] < d:
		cc += arr[r][1]
		r += 1
	ans = max(ans, cc)
	cc -= arr[i][1]
print(ans)


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

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

def getStrs():
	return [s for s in input().split()]

def getStr():
	return input()

def listStr():
	return list(input())

def solve():
	(N, D) = getInts()
	friends = []
	prefix_sums = []
	curr_sum = 0
	for n in range(N):
		(money, friendship) = getInts()
		friends.append((money, friendship))
	friends.sort()
	prefix_sums = []
	for n in range(N):
		curr_sum += friends[n][1]
		prefix_sums.append(curr_sum)
	last_friend = 0
	best = 0
	for first_friend in range(N):
		min_money = friends[first_friend][0]
		last_friend = max(last_friend, first_friend)
		while last_friend < N - 1 and friends[last_friend + 1][0] < min_money + D:
			last_friend += 1
		if first_friend == 0:
			curr_val = prefix_sums[last_friend]
		else:
			curr_val = prefix_sums[last_friend] - prefix_sums[first_friend - 1]
		best = max(best, curr_val)
		if last_friend == N - 1:
			return best
ans = solve()
print(ans)


def readnums():
	return list(map(lambda x: int(x), input().split(' ')))
(n, d) = readnums()
fr = []
for i in range(n):
	fr.append(tuple(readnums()))
fr.sort()
ans = 0
min_money = 0
friendship = 0
i = 0
j = 0
while i < n:
	min_money = fr[i][0]
	ans = max(ans, friendship)
	if i > j:
		j = i
	while j < n and abs(fr[j][0] - min_money) < d:
		friendship += fr[j][1]
		j += 1
		ans = max(ans, friendship)
	friendship -= fr[i][1]
	i += 1
print(ans)


(n, d) = map(int, input().split(' '))
p = []
for _ in range(n):
	q = list(map(int, input().split(' ')))
	p.append(q)
p = sorted(p, key=lambda k: k[0])
finalmax = curmax = p1 = p2 = 0
while p2 < n:
	if p[p2][0] - p[p1][0] < d:
		curmax += p[p2][1]
		p2 += 1
		finalmax = max(finalmax, curmax)
	else:
		curmax -= p[p1][1]
		p1 += 1
print(finalmax)


import operator

class PII:

	def __init__(self, F, S):
		self.F = F
		self.S = S
(n, d) = [int(x) for x in input().split()]
a = []
for i in range(n):
	(F, S) = [int(x) for x in input().split()]
	a.append(PII(F, S))
a.sort(key=operator.attrgetter('F'))
idx = 0
mx = a[0].S
amt = a[0].S
for i in range(1, n):
	if a[i].F - a[idx].F < d:
		amt += a[i].S
	else:
		mx = max(mx, amt)
		j = idx
		while a[i].F - a[j].F >= d:
			amt -= a[j].S
			j += 1
		idx = j
		amt += a[i].S
mx = max(mx, amt)
print(mx)


(n, d) = map(int, input().split())
a = []
for i in range(n):
	(x, y) = map(int, input().split())
	a.append((x, y))
a.sort()
sum1 = 0
m = 0
j = 0
for i in range(n):
	while a[i][0] - a[j][0] >= d:
		sum1 = sum1 - a[j][1]
		j = j + 1
	sum1 = sum1 + a[i][1]
	m = max(m, sum1)
print(m)


(n, d) = map(int, input().split())
a = []
for _ in range(n):
	(x, y) = map(int, input().split())
	a.append([x, y])
a.sort()
ans = a[0][1]
res = a[0][1]
p1 = 0
p2 = 0
while p2 < n - 1:
	if a[p2 + 1][0] - a[p1][0] < d:
		p2 += 1
		ans += a[p2][1]
		if ans > res:
			res = ans
	else:
		ans = ans - a[p1][1]
		p1 += 1
print(res)


(n, d) = list(map(int, input().split()))
l = []
for i in range(n):
	(m, s) = list(map(int, input().split()))
	l.append([m, s])
l.sort()
i = 0
s = 0
m_x = 0
for k in range(n):
	s += l[k][1]
	while l[k][0] - l[i][0] >= d:
		s -= l[i][1]
		i += 1
	m_x = max(m_x, s)
print(m_x)


import sys
from bisect import bisect_right

def main():
	(n, d) = map(int, input().split())
	friends = sorted((tuple((int(c) for c in line.split())) for line in sys.stdin.readlines()))
	money = [e[0] for e in friends]
	friendship_sum = [0]
	for (_, e) in friends:
		friendship_sum.append(friendship_sum[-1] + e)
	_min = friends[0][0]
	i = 1
	start = 0
	ans = friends[0][1]
	while i < n:
		cur = money[i]
		diff = cur - _min
		_min = min(_min, cur)
		if diff >= d:
			start = bisect_right(money, cur - d)
			_min = money[start]
		friendship = friendship_sum[i + 1] - friendship_sum[start]
		ans = max(ans, friendship)
		i += 1
	print(ans)
main()


p = lambda : map(int, input().split())
(a, b) = p()
f = [[*p()] for _ in ' ' * a]
f = sorted(f)
(i, j, k, m) = (0, 0, 0, 0)
while j < a:
	if f[j][0] - f[i][0] < b:
		k += f[j][1]
		m = max(m, k)
		j += 1
	else:
		k -= f[i][1]
		i += 1
print(m)


n = input().split(' ')
(n, d) = (int(n[0]), int(n[1]))
a = [0] * n
for i in range(n):
	m = input().split(' ')
	a[i] = [int(m[0]), int(m[1])]
a.sort()
maxD = 0
count = a[0][1]
(i, j) = (0, 1)
while j < n:
	if a[j][0] - a[i][0] < d:
		count += a[j][1]
		j += 1
	else:
		maxD = max(count, maxD)
		count -= a[i][1]
		i += 1
print(max(count, maxD))


from bisect import *
(n, d) = map(int, input().split())
tp = list()
for i in range(n):
	(m, s) = map(int, input().split())
	tp.append((m, s))
tp.sort(key=lambda x: x[0])
m = list()
s = list()
for i in range(n):
	m.append(tp[i][0])
	s.append(tp[i][1])
ps = list()
sn = 0
for i in range(n):
	sn += s[i]
	ps.append(sn)
mx = -1000
for i in range(n):
	ind = bisect_left(m, m[i] + d)
	if i != 0:
		mx = max(mx, ps[ind - 1] - ps[i - 1])
	else:
		mx = max(mx, ps[ind - 1])
print(mx)


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 sort_list(list1, list2):
	zipped_pairs = zip(list2, list1)
	z = [x for (_, x) in sorted(zipped_pairs)]
	return z
(n, k) = map(int, input().split())
a = [0] * n
b = [0] * n
for i in range(n):
	(a[i], b[i]) = map(int, input().split())
b = sort_list(b, a)
a.sort()
start = 0
ans = b[0]
ma = 0
i = 1
while i < n:
	if a[i] - a[start] < k:
		ans += b[i]
		i += 1
	else:
		ma = max(ma, ans)
		ans -= b[start]
		start += 1
ma = max(ma, ans)
print(ma)


(n, k) = map(int, input().split())
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
l.sort(key=lambda x: x[0])
(ans, maxx) = (0, 0)
ans = 0
(i, j) = (0, 0)
while i < n:
	while j < n and l[j][0] - l[i][0] < k:
		ans += l[j][1]
		j += 1
	maxx = max(ans, maxx)
	ans -= l[i][1]
	i += 1
print(maxx)


r = lambda : list(map(int, input().split()))
(n, d) = r()
a = sorted((tuple(r()) for i in range(n)))
i = 0
Min = a[i][0]
Max = cur = 0
for (m, s) in a:
	cur += s
	if m - Min >= d:
		while m - a[i][0] >= d:
			cur -= a[i][1]
			i += 1
		Min = a[i][0]
	Max = max(Max, cur)
print(Max)


(n, m) = map(int, input().split())
amig = []
for i in range(n):
	(d, a) = map(int, input().split())
	amig.append((d, a))
amig.sort()
ip = 0
maxi = 0
atual = 0
for i in range(0, n):
	if amig[i][0] - amig[ip][0] < m:
		atual += amig[i][1]
	else:
		if atual > maxi:
			maxi = atual
		while amig[i][0] - amig[ip][0] >= m:
			atual -= amig[ip][1]
			ip += 1
		atual += amig[i][1]
print(max(maxi, atual))


def binarySearch(aList, target, low, high):
	while low <= high:
		mid = (low + high) // 2
		if aList[mid][0] > target:
			high = mid - 1
		else:
			low = mid + 1
	return low - 1
nd = input().split()
nd = [int(i) for i in nd]
data = []
for i in range(nd[0]):
	line = input().split()
	line = [int(j) for j in line]
	data.append(line)
data.sort()
ff_list = []
for i in range(nd[0]):
	if i == 0:
		ff_list.append(data[0][1])
	else:
		ff_list.append(ff_list[i - 1] + data[i][1])
maxff = 0
for i in range(nd[0]):
	last = binarySearch(data, data[i][0] + nd[1] - 1, i, nd[0] - 1)
	if i != 0:
		if ff_list[last] - ff_list[i - 1] > maxff:
			maxff = ff_list[last] - ff_list[i - 1]
	elif ff_list[last] > maxff:
		maxff = ff_list[last]
print(maxff)


import random, math
from copy import deepcopy as dc
from bisect import bisect_left, bisect_right

def solution(pairs, d):
	pairs.sort(key=lambda x: x[0])
	i = 0
	pre = []
	prek = []
	sk = 0
	for i in range(len(pairs)):
		sk += pairs[i][1]
		pre.append(pairs[i][0])
		prek.append(sk)
	maxi = float('-inf')
	for i in range(len(pairs)):
		mid = bisect_right(pre, pre[i] + d - 1, i + 1, len(pairs))
		m = prek[mid - 1]
		if i != 0:
			m -= prek[i - 1]
		if m > maxi:
			maxi = dc(m)
	return maxi

def input_test():
	(n, d) = map(int, input().strip().split(' '))
	pairs = []
	for i in range(n):
		li = list(map(int, input().strip().split(' ')))
		pairs.append(li)
	out = solution(pairs, d)
	print(out)
input_test()


(a, b) = map(int, input().split())
c = 0
f = 0
d = 0
e = list()
for _ in range(a):
	(g, h) = map(int, input().split())
	e.append([g, h])
e.sort()
for i in range(a):
	c = c + e[i][1]
	while e[i][0] - e[d][0] >= b:
		c = c - e[d][1]
		d = d + 1
	f = max(f, c)
print(f)


def ans(f, n, d):
	if n == 1:
		return f[0][1]
	ans = f[0][1]
	tmp_ans = f[0][1]
	i = 0
	j = 1
	while j < n:
		if i == j:
			tmp_ans = f[j][1]
			j += 1
			if tmp_ans > ans:
				ans = tmp_ans
		elif abs(f[i][0] - f[j][0]) < d:
			tmp_ans += f[j][1]
			j += 1
			if tmp_ans > ans:
				ans = tmp_ans
		else:
			while abs(f[i][0] - f[j][0]) >= d and i < j:
				tmp_ans -= f[i][1]
				i += 1
	return ans
(n, d) = map(int, input().split())
friends = []
for _ in range(n):
	tmp = [int(i) for i in input().split()]
	friends.append(tmp)
friends.sort()
print(ans(friends, n, d))


def getIndex(a, k, start, end, val, i):
	if start == end:
		if val - a[start][0] < k:
			return start
		return i
	mid = (start + end) // 2
	if val - a[mid][0] < k:
		return getIndex(a, k, start, mid, val, i)
	return getIndex(a, k, mid + 1, end, val, i)
(n, k) = map(int, input().split())
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
a.sort(key=lambda x: x[0])
pref = [0 for i in range(n)]
glob = a[0][1]
pref[0] = a[0][1]
for i in range(1, n):
	pref[i] = pref[i - 1] + a[i][1]
for i in range(1, n):
	temp = getIndex(a, k, 0, i - 1, a[i][0], i)
	glob = max(glob, pref[i] - (pref[temp - 1] if temp - 1 >= 0 else 0))
print(glob)


[friendsSize, moneyDiff] = [int(x) for x in input().split()]
friends = []
for i in range(friendsSize):
	(friendMoney, currentPoints) = map(int, input().split())
	friends.append([friendMoney, currentPoints])
friends = sorted(friends)
currentPoints = 0
maxPoints = 0
j = 0
for i in range(friendsSize):
	while j < friendsSize and abs(friends[i][0] - friends[j][0]) < moneyDiff:
		currentPoints += friends[j][1]
		j += 1
	if currentPoints >= maxPoints:
		maxPoints = currentPoints
	currentPoints -= friends[i][1]
print(maxPoints)


l = list(map(int, input().rstrip().split()))
a = []
for i in range(l[0]):
	k = list(map(int, input().rstrip().split()))
	a.append(k)
a.sort()
end = 0
strat = 0
trust = 0
subtrust = 0
k = 0
while end < len(a):
	if abs(a[strat][0] - a[end][0]) < l[1]:
		subtrust += a[end][1]
		end += 1
		trust = max(trust, subtrust)
	else:
		subtrust -= a[strat][1]
		strat += 1
print(trust)


(n, d) = [int(x) for x in input().split()]
s = []
while n:
	s.append([int(x) for x in input().split()])
	n -= 1
s = sorted(s, key=lambda x: x[0], reverse=True)
st = 0
suma = 0
maxim = -1
for dr in range(len(s)):
	suma += s[dr][1]
	while abs(s[st][0] - s[dr][0]) >= d:
		suma -= s[st][1]
		st += 1
	if suma > maxim:
		maxim = suma
print(maxim)


def solve(inp, d):
	inp = sorted(inp, key=lambda x: x[0])
	p1 = 0
	p2 = 0
	n = len(inp)
	maxfnd = 0
	max1 = maxfnd
	while p2 < n:
		if inp[p2][0] - inp[p1][0] < d:
			maxfnd += inp[p2][1]
			p2 += 1
		else:
			maxfnd -= inp[p1][1]
			p1 += 1
		max1 = max(max1, maxfnd)
	return max1
(n, s) = map(int, input().split())
in1 = []
for i in range(n):
	in1.append(list(map(int, input().split())))
print(solve(in1, s))


(n, d) = list(map(int, input().split()))
F = []
for i in range(n):
	F.append(list(map(int, input().split())))
F = sorted(F, key=lambda x: x[0])
f_factor = 0
j = 0
ans = -1
for i in range(n):
	if i != 0:
		f_factor -= F[i - 1][1]
	while j < n:
		if F[j][0] - F[i][0] >= d:
			break
		f_factor += F[j][1]
		j += 1
	ans = max(ans, f_factor)
print(ans)


(n, d) = input().split()
(n, d) = (int(n), int(d))
l = []
for _ in range(n):
	x = input().split()
	l.append((int(x[0]), int(x[1])))

def key(pair):
	return pair[0]
l.sort(key=key)
i = 0
j = 0
sum = 0
max = 0
while i < n and j < n:
	if l[j][0] - l[i][0] >= d:
		sum -= l[i][1]
		i -= -1
	else:
		sum += l[j][1]
		j -= -1
	if sum > max:
		max = sum
print(max)


(n, f) = input().split()
n = int(n)
f = int(f)
a = []
for i in range(n):
	(x, y) = input().split()
	a.append((int(x), int(y)))
a = sorted(a)
s = a[0][1]
mx = s
k = 0
for i in range(1, len(a)):
	if a[i][0] - a[k][0] < f:
		s = s + a[i][1]
	else:
		s = s - a[k][1] + a[i][1]
		for j in range(k + 1, i + 1):
			if a[i][0] - a[j][0] < f:
				s = s
				k = j
				break
			else:
				s = s - a[j][1]
				k = j
	if s > mx:
		mx = s
print(mx)


(n, poorAmount) = list(map(int, input().split(' ')))
everythingList = []
moneyList = []
friendshipFactorList = []
for _ in range(n):
	(money, friendshipFactor) = list(map(int, input().split(' ')))
	everythingList.append((money, friendshipFactor))
everythingList.sort(key=lambda x: x[0])
i = 0
j = 0
endingSequence = False
rollingFriendShip = everythingList[i][1]
maxFriendShip = rollingFriendShip
while not j + 1 >= n:
	totalMoneyDif = abs(everythingList[j][0] - everythingList[i][0])
	if totalMoneyDif < poorAmount and i + 1 < n:
		maxFriendShip = max(maxFriendShip, rollingFriendShip)
		i += 1
		rollingFriendShip += everythingList[i][1]
	else:
		if abs(everythingList[j][0] - everythingList[i][0]) < poorAmount:
			maxFriendShip = max(maxFriendShip, rollingFriendShip)
			if i + 1 == n and rollingFriendShip < maxFriendShip:
				break
		rollingFriendShip -= everythingList[j][1]
		j += 1
if abs(everythingList[j][0] - everythingList[i][0]) < poorAmount:
	maxFriendShip = max(maxFriendShip, rollingFriendShip)
print(maxFriendShip)


(n, d) = map(int, input().split())
f = []
for i in range(n):
	f.append(list(map(int, input().split())))
f.sort()
pf = [0]
for i in range(n):
	pf.append(pf[-1] + f[i][1])
l = 0
r = 0
mx = 0
while r < n:
	if f[r][0] - f[l][0] < d:
		mx = max(mx, pf[r + 1] - pf[l])
		r += 1
	else:
		l += 1
print(mx)


firstLine = input().split(' ')
noOfFriends = int(firstLine[0])
diff = int(firstLine[1])
friends = []
for index in range(noOfFriends):
	desc = input().split(' ')
	friends.append((int(desc[0]), int(desc[1])))
friends.sort()
left = 0
right = 1
maxFriendship = friends[0][1]
friendship = friends[0][1]
while right <= noOfFriends - 1:
	friendship += friends[right][1]
	while friends[right][0] - friends[left][0] >= diff:
		friendship -= friends[left][1]
		left += 1
	if maxFriendship < friendship:
		maxFriendship = friendship
	right += 1
print(maxFriendship)


import math
(n, d) = [int(x) for x in input().split()]
friends = []
for i in range(n):
	friends.append(tuple((int(x) for x in input().split())))
friends.sort()
friendship_max = 0
friendship = 0
j = 0
for i in range(len(friends)):
	while j < n and friends[j][0] - friends[i][0] < d:
		friendship += friends[j][1]
		j += 1
	if friendship > friendship_max:
		friendship_max = friendship
		friendship_argmax = (i, j)
	friendship -= friends[i][1]
print(friendship_max)


(n, m) = map(int, input().split())
a = []
for _ in range(n):
	a.append(list(map(int, input().split())))
a.sort()
s = 0
ans = 0
cm = 0
for e in range(n):
	cm += a[e][1]
	while a[e][0] - a[s][0] >= m:
		cm -= a[s][1]
		s += 1
	ans = max(ans, cm)
print(ans)


from sys import stdin
stdin.readline

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

def it():
	return int(stdin.readline().strip())
v = []
(n, d) = mp()
for i in range(n):
	(a, b) = mp()
	v += [[a, b]]
v.sort()
ma = 0
ans = v[0][1]
(i, j) = (0, 1)
while i < n and j < n:
	if abs(v[j][0] - v[i][0]) >= d:
		if ans > ma:
			ma = ans
		ans -= v[i][1]
		i += 1
	else:
		ans += v[j][1]
		j += 1
print(max(ans, ma))


class MaximumFriendshipWithinMoneyRangeProblem:

	def __init__(self):
		(self.numFriends, self.moneyRange, self.friends) = self.getInput()
		self.solution = self.computeMaximumFriendshipWithinMoneyRange()

	def getInput(self):
		(numFriends, moneyDistance) = map(int, input().split())
		friends = [tuple(map(int, input().split())) for _ in range(numFriends)]
		return (numFriends, moneyDistance, friends)

	def computeMaximumFriendshipWithinMoneyRange(self):
		self.friends.sort()
		rangeFriendshipFactor = 0
		maxFriendshipFactor = 0
		poorestInMoneyRange = 0
		for richestInMoneyRange in range(self.numFriends):
			rangeFriendshipFactor += self.getFriendshipFactor(richestInMoneyRange)
			while self.poorestFeelsPoor(poorestInMoneyRange, richestInMoneyRange):
				rangeFriendshipFactor -= self.getFriendshipFactor(poorestInMoneyRange)
				poorestInMoneyRange += 1
			maxFriendshipFactor = max(rangeFriendshipFactor, maxFriendshipFactor)
		return maxFriendshipFactor

	def getFriendshipFactor(self, friend):
		return self.friends[friend][1]

	def poorestFeelsPoor(self, poorest, richest):
		return self.getMoney(richest) - self.getMoney(poorest) >= self.moneyRange

	def getMoney(self, friend):
		return self.friends[friend][0]

	def getSolution(self):
		return self.solution
print(MaximumFriendshipWithinMoneyRangeProblem().getSolution())


(n, d) = map(int, input().split())
l = sorted([[*map(int, input().split())] for _ in ' ' * n])
j = a = A = 0
for i in range(n):
	a += l[i][1]
	while l[i][0] - l[j][0] >= d:
		a -= l[j][1]
		j += 1
	A = max(A, a)
print(A)


class Friend:

	def __init__(self, m, s):
		self.m = m
		self.s = s
(n, d) = list(map(int, input().split()))
friends = []
for i in range(n):
	(m, s) = list(map(int, input().split()))
	friends.append(Friend(m, s))
friends.sort(key=lambda f: f.m)
max_score = 0
right = 0
curr = 0
for left in range(n):
	while right < n and friends[right].m < d + friends[left].m:
		curr += friends[right].s
		right += 1
	max_score = max(max_score, curr)
	curr -= friends[left].s
print(max_score)


(a, d) = map(int, input().split())
ans = []
for i in range(a):
	z = list(map(int, input().split()))
	ans.append(z)
ans.sort(key=lambda x: (x[0], x[1]))
l = 0
r = 0
maxa = []
mi = 0
i = 0
while l <= r and r < len(ans):
	if ans[r][0] - ans[l][0] < d:
		mi += ans[i][1]
		r += 1
		i += 1
	else:
		maxa.append(mi)
		l += 1
		mi = maxa[-1] - ans[l - 1][1]
maxa.append(mi)
print(max(maxa))


(n, d) = map(int, input().split())
values = []
for i in range(n):
	(m, f) = input().split()
	values.append((int(m), int(f)))
values.sort()
(l, r) = (0, 1)
(ans, curr) = (values[0][1], values[0][1])
while r < n:
	curr += values[r][1]
	while l < r and values[r][0] - values[l][0] >= d:
		curr -= values[l][1]
		l += 1
	ans = max(ans, curr)
	r += 1
print(ans)


(n, d) = map(int, input().split())
friends = [list(map(int, input().split())) for _ in range(n)]
friends.sort()
s = [friends[0][1]]
for i in range(1, n):
	s.append(s[i - 1] + friends[i][1])
mx = 0
for i in range(n):
	low = i + 1
	high = n
	while low < high:
		mid = low + (high - low) // 2
		if friends[mid][0] - friends[i][0] >= d:
			high = mid
		else:
			low = mid + 1
	if i == 0:
		total = s[low - 1]
	else:
		total = s[low - 1] - s[i - 1]
	if mx < total:
		mx = total
print(mx)


import sys
from collections import Counter
from math import factorial
input = sys.stdin
output = sys.stdout

def read_int():
	return [int(x) for x in input.readline().rstrip().split()]
(n, d) = read_int()
friends = list()
for _ in range(n):
	(m, s) = read_int()
	friends.append((m, s))
friends.sort(key=lambda e: e[0])
(answer, candidate) = (friends[0][1], friends[0][1])
(l, r) = (-1, 0)
while r + 1 < n:
	if l >= 0:
		candidate -= friends[l][1]
	l += 1
	while r + 1 < n and friends[l][0] + d > friends[r + 1][0]:
		r += 1
		candidate += friends[r][1]
	answer = max(answer, candidate)
output.write('%d\n' % answer)


(n, d) = map(int, input().split())
friends = []
(s, ans, ind) = (0, 0, 0)
for i in range(n):
	friends.append(list(map(int, input().split())))
friends.sort(key=lambda numb: numb[0])
for j in range(n):
	s += friends[j][1]
	while friends[j][0] - friends[ind][0] >= d:
		s -= friends[ind][1]
		ind += 1
	ans = max(ans, s)
print(ans)


(n, d) = map(int, input().split())
li = sorted([list(map(int, input().split())) for i in range(n)])
temp = ans = li[0][1]
j = 0
for i in range(1, n):
	while li[i][0] >= li[j][0] + d:
		temp -= li[j][1]
		j += 1
	temp += li[i][1]
	ans = max(temp, ans)
print(ans)


(n, d) = map(int, input().split())
l = []
for i in range(n):
	(a, b) = map(int, input().split())
	l.append([a, b])
l.sort()
ans = l[0][1]
c = l[0][1]
i = 0
j = 1
while j < n:
	if l[j][0] - l[i][0] < d:
		c += l[j][1]
		j += 1
	else:
		c -= l[i][1]
		i += 1
	ans = max(ans, c)
print(ans)


import sys
import math
import operator as op
from functools import reduce

def read_line():
	return sys.stdin.readline()[:-1]

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

def read_int_line():
	return [int(v) for v in sys.stdin.readline().split()]

def read_float_line():
	return [float(v) for v in sys.stdin.readline().split()]

def ncr(n, r):
	r = min(r, n - r)
	numer = reduce(op.mul, range(n, n - r, -1), 1)
	denom = reduce(op.mul, range(1, r + 1), 1)
	return numer / denom
t = 1
for i in range(t):
	(n, d) = read_int_line()
	li = []
	for i in range(n):
		(m, f) = read_int_line()
		li.append([m, f])
	li = sorted(li, key=lambda x: x[0])
	l = 0
	r = 0
	ans = -1
	cur = 0
	while l <= r and r < n:
		while l <= r and abs(li[l][0] - li[r][0]) >= d:
			cur -= li[l][1]
			l += 1
		while r < n and abs(li[l][0] - li[r][0]) < d:
			cur += li[r][1]
			r += 1
		ans = max(ans, cur)
	print(ans)


from bisect import *
(n, d) = map(int, input().split())
lol = []
for _ in range(n):
	(m, s) = map(int, input().split())
	lol.append((m, s))
lol.sort()
pre = [0]
for c in lol:
	pre.append(pre[-1] + c[1])
ans = 0
for i in range(n):
	j = lol[i]
	b2 = bisect_right(lol, (j[0] + d - 1, 10 ** 100))
	ans = max(ans, pre[b2] - pre[i])
print(ans)


(a, b) = map(int, input().split())
x = [[0, 0]]
mx = 0
c1 = 1
c2 = 1
for i in range(a):
	x.append(list(map(int, input().split())))
x.sort()
for i in range(1, a + 1):
	x[i][1] = x[i - 1][1] + x[i][1]
for c1 in range(0, a + 1):
	c2 = max(c1, c2)
	while c2 < a + 1 and x[c2][0] < x[c1][0] + b:
		c2 += 1
	mx = max(mx, x[c2 - 1][1] - x[c1 - 1][1])
	if mx == 19:
		print(c2, c1)
print(mx)


(n, d) = map(int, input().split())
mat = []
for i in range(n):
	(m, s) = map(int, input().split())
	mat.append([m, s])
mat.sort(key=lambda x: x[0])
dp = [0] * (n + 1)
for i in range(1, n + 1):
	dp[i] = dp[i - 1] + mat[i - 1][1]
ans = mat[0][1]
i = 0
j = 0
while i < n and j < n:
	if mat[j][0] - mat[i][0] < d:
		ans = max(ans, dp[j + 1] - dp[i])
		j += 1
	else:
		i += 1
print(ans)


(n, d) = map(int, input().split())
li = []
for i in range(n):
	(m, s) = map(int, input().split())
	li.append((m, s))
li = sorted(li)
total = li[0][1]
maxTotal = li[0][1]
p = 0
for i in range(1, n):
	while li[i][0] >= d + li[p][0]:
		total -= li[p][1]
		p += 1
	total += li[i][1]
	maxTotal = max(maxTotal, total)
print(maxTotal)


friend = []
(n, d) = [int(i) for i in input().split(' ')]
for i in range(n):
	friend.append([int(i) for i in input().split(' ')])
friend = sorted(friend, key=lambda fr: fr[0])
ans = 0
cur = 0
rich = iter(friend)
i = next(rich)
for poor in friend:
	try:
		while i[0] < poor[0] + d:
			cur += i[1]
			i = next(rich)
		ans = max(ans, cur)
		cur -= poor[1]
	except StopIteration:
		break
ans = max(ans, cur)
print(ans)


__author__ = 'User'

def p(x):
	l = 0
	r = n
	while l + 1 < r:
		m = (l + r) // 2
		if arr[m][0] <= x:
			l = m
		else:
			r = m
	return l

def p2(x):
	l = -1
	r = n - 1
	while l + 1 < r:
		m = (l + r) // 2
		if arr[m][0] < x:
			l = m
		else:
			r = m
	return r
(n, d) = map(int, input().split())
arr = [0] * n
summ = [0] * n
s = 0
for i in range(n):
	arr[i] = tuple(map(int, input().split()))
arr.sort()
for i in range(n):
	summ[i] = s + arr[i][1]
	s += arr[i][1]
summ.append(0)
mx = 0
c = 0
for i in arr:
	r = p(i[0] + (d - 1))
	l = p2(i[0])
	s = summ[r] - summ[l - 1]
	mx = max(mx, s)
print(mx)


import bisect
from collections import Counter, defaultdict
from sys import stdin, stdout
input = stdin.readline
I = lambda : int(input())
M = lambda : map(int, input().split())
LI = lambda : list(map(int, input().split()))
(n, m) = M()
d = defaultdict(int)
b = []
ans = 0
for _ in range(n):
	(a, b) = M()
	d[a] += b
	ans = max(ans, d[a])
c = list(d.keys())
c.sort()
e = [0]
val = 0
for i in range(len(c)):
	val += d[c[i]]
	e += [val]
for i in range(len(c)):
	f = c[i] + m
	ind = bisect.bisect_left(c, f)
	ans = max(ans, e[ind] - e[i])
print(ans)


[n, d] = list(map(int, input().split()))
a = [list(map(int, input().split())) for _ in range(n)]
a.sort()
ans = a[0][1]
res = a[0][1]
p1 = 0
p2 = 0
while p2 < n - 1:
	if a[p2 + 1][0] - a[p1][0] < d:
		p2 += 1
		ans += a[p2][1]
		if ans > res:
			res = ans
	else:
		ans -= a[p1][1]
		p1 += 1
print(res)


(n, d) = [int(x) for x in input().split()]
ms = []
for i in range(n):
	msi = [int(x) for x in input().split()]
	ms.append(msi)
ms = sorted(ms)
(l, u) = (0, 0)
for i in range(n):
	if ms[i][0] - ms[0][0] >= d:
		u = i - 1
		break
if ms[n - 1][0] - ms[0][0] < d:
	u = n - 1
psum = [ms[0][1]] * n
for i in range(1, n):
	psum[i] = psum[i - 1] + ms[i][1]
ans = psum[u]
for i in range(1, n):
	l = i
	for j in range(u + 1, n):
		if ms[j][0] - ms[i][0] >= d:
			u = j - 1
			break
	if ms[n - 1][0] - ms[i][0] < d:
		u = n - 1
	ans = max(ans, psum[u] - psum[l - 1])
print(ans)


(n, d) = map(int, input().split())
arr = sorted([list(map(int, input().split())) for i in range(n)])
(j, s, res) = (0, arr[0][1], arr[0][1])
for i in range(1, n):
	while arr[i][0] - arr[j][0] >= d:
		s -= arr[j][1]
		j += 1
	s += arr[i][1]
	res = max(s, res)
print(res)


(n, d) = map(int, input().split())
counter = 0
maximum = 0
total = 0
list = sorted([list(map(int, input().split())) for x in range(n)])
for i in range(n):
	while counter < n and list[counter][0] - list[i][0] < d:
		total += list[counter][1]
		counter += 1
	maximum = max(maximum, total)
	total -= list[i][1]
print(maximum)


(n, d) = map(int, input().split(' '))
lst = [tuple(map(int, input().split(' '))) for _ in range(n)]
lst.sort(key=lambda x: x[0])
left_index = 0
cur_frd = lst[left_index][1]
mx = cur_frd
cur_index = 1
while cur_index < n:
	while lst[cur_index][0] - lst[left_index][0] < d:
		cur_frd += lst[cur_index][1]
		cur_index += 1
		if cur_frd > mx:
			mx = cur_frd
		if cur_index == n:
			break
	cur_frd -= lst[left_index][1]
	left_index += 1
print(mx)


import sys
import math
import collections
import bisect
from collections import deque as queue

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

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

def get_string():
	return sys.stdin.readline().strip()
for t in range(1):
	(n, m) = get_ints()
	ans = []
	for i in range(n):
		ans.append(get_list())
	ans.sort()
	start = 0
	end = 0
	maxim = 0
	val = 0
	while end < n and start < n:
		if ans[end][0] - ans[start][0] < m:
			val += ans[end][1]
			end += 1
		else:
			val -= ans[start][1]
			start += 1
		maxim = max(val, maxim)
	print(maxim)


line = input()
(n, d) = map(int, line.split())
ms = []
for i in range(n):
	line = input()
	tmp = list(map(int, line.split()))
	ms.append(tmp)
ms = sorted(ms, key=lambda ms: ms[0])
i = 0
j = 0
ans = 0
while j < n and abs(ms[i][0] - ms[j][0]) < d:
	ans += ms[j][1]
	j += 1
maxx = ans
while j < n:
	ans += ms[j][1]
	while abs(ms[i][0] - ms[j][0]) >= d:
		ans -= ms[i][1]
		i += 1
	if maxx < ans:
		maxx = ans
	j += 1
print(maxx)


def sf(a):
	return -a[0]
inp = input().split()
n = int(inp[0])
d = int(inp[1])
arr = []
for i in range(0, n):
	dat = [int(x) for x in input().split()]
	arr.append(dat)
arr.sort(key=sf)
l = r = 0
summ = arr[0][1]
ans = arr[0][1]
while r < n - 1:
	if arr[l][0] - arr[r + 1][0] < d:
		summ += arr[r + 1][1]
		r += 1
	else:
		summ -= arr[l][1]
		l += 1
	ans = max(ans, summ)
print(ans)


from operator import itemgetter
(n, d) = map(int, input().split())
fnd = []
for i in range(n):
	fnd.append([0, 0])
	fnd[i] = list(map(int, input().split()))
fnd.sort(key=lambda x: x[0])
tmp = fnd[0][1]
mx = tmp
j = 0
for i in range(n):
	if j == n - 1:
		break
	while fnd[j + 1][0] - fnd[i][0] < d:
		tmp += fnd[j + 1][1]
		j += 1
		if j == n - 1:
			break
	if tmp > mx:
		mx = tmp
	tmp -= fnd[i][1]
print(mx)


def find_company(friends, d):

	def mergesort_tuples(tuples, index):

		def merge(A, B):
			(i, j) = (0, 0)
			result = []
			while i < len(A) and j < len(B):
				if A[i][index] < B[j][index]:
					result.append(A[i])
					i += 1
				else:
					result.append(B[j])
					j += 1
			result += A[i:]
			result += B[j:]
			return result

		def divide(tuples):
			if len(tuples) > 1:
				middle = len(tuples) // 2
				return merge(divide(tuples[:middle]), divide(tuples[middle:]))
			return tuples
		return divide(tuples)

	def solve(friends, d):
		friends = mergesort_tuples(friends, 0)
		left_ptr = 0
		right_ptr = 0
		current_friendship = 0
		max_friendship = 0
		while right_ptr < len(friends):
			if friends[right_ptr][0] - friends[left_ptr][0] < d:
				current_friendship += friends[right_ptr][1]
				right_ptr += 1
			else:
				max_friendship = max(current_friendship, max_friendship)
				current_friendship -= friends[left_ptr][1]
				left_ptr += 1
		max_friendship = max(current_friendship, max_friendship)
		return max_friendship
	return solve(friends, d)
(n, d) = [int(x) for x in input().split()]
friends = []
for _ in range(n):
	friends.append(tuple([int(x) for x in input().split()]))
print(find_company(friends, d))


(N, D) = map(int, input().split())
friends = [tuple(map(int, input().split())) for i in range(N)]
friends.sort()
friendship = 0
hi = 0
res = 0
for lo in range(N):
	while hi < N and friends[hi][0] - friends[lo][0] < D:
		friendship += friends[hi][1]
		hi += 1
	res = max(res, friendship)
	friendship -= friends[lo][1]
print(res)


(n, d) = map(int, input().split())
v = sorted([list(map(int, input().split())) for i in range(n)], key=lambda x: x[0])
sum = v[0][1]
sol = v[0][1]
b = 0
for i in range(1, n):
	while v[i][0] >= d + v[b][0]:
		sum -= v[b][1]
		b += 1
	sum += v[i][1]
	sol = max(sum, sol)
print(sol)


firstLineInput = input()
firstLineInput = firstLineInput.split(' ')
repetition = int(firstLineInput[0])
dick = int(firstLineInput[1])
friendship = []
i = 0
while i != repetition:
	friendInput = input()
	friendInput = friendInput.split(' ')
	friendship.append([int(friendInput[0]), int(friendInput[1])])
	i += 1
friendship.sort()
start = 0
end = 0
ref = 0
n = len(friendship)
totalSum = 0
while end < n:
	while end < n and friendship[end][0] - friendship[start][0] < dick:
		totalSum += friendship[end][1]
		end += 1
	if totalSum > ref:
		ref = totalSum
	totalSum -= friendship[start][1]
	start += 1
print(ref)


import sys

def fastio():
	from io import StringIO
	from atexit import register
	global input
	sys.stdin = StringIO(sys.stdin.read())
	input = lambda : sys.stdin.readline().rstrip('\r\n')
	sys.stdout = StringIO()
	register(lambda : sys.__stdout__.write(sys.stdout.getvalue()))
fastio()

def debug(*var, sep=' ', end='\n'):
	print(*var, file=sys.stderr, end=end, sep=sep)
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
(n, d) = I()
a = [(0, 0)]
for i in range(n):
	(x, y) = I()
	a.append((x, y))
a.sort()
j = 0
ans = 0
cur = 0
for i in range(1, n + 1):
	cur += a[i][1]
	while a[i][0] - a[j][0] >= d:
		cur -= a[j][1]
		j += 1
	ans = max(ans, cur)
print(ans)


(n, d) = map(int, input().split())
ms = []
for o in range(n):
	(m, s) = map(int, input().split())
	ms.append((m, s))
ms.sort()
k = 0
maximum = 0
s = 0
for i in range(n):
	s += ms[i][1]
	while ms[i][0] - ms[k][0] >= d:
		s -= ms[k][1]
		k += 1
	maximum = max(maximum, s)
print(maximum)


def solve(m, d):
	m.sort()
	res = 0
	curr = 0
	(i, j) = (0, 0)
	while j < len(m):
		if m[j][0] - m[i][0] >= d:
			curr -= m[i][1]
			i += 1
		else:
			curr += m[j][1]
			res = max(res, curr)
			j += 1
	return res
(n, d) = map(int, input().split())
f = []
for i in range(n):
	(mi, fi) = map(int, input().split())
	f.append((mi, fi))
print(solve(f, d))


(n, d) = list(map(int, input().split()))
m = []
s = []
for _ in range(n):
	(m_, s_) = list(map(int, input().split()))
	m.append(m_)
	s.append(s_)
data = sorted(zip(m, s), key=lambda x: x[0])
m = [d[0] for d in data]
s = [d[1] for d in data]
j = 0
i = 0
mx = s[i]
res = []
while i < n:
	res.append(mx)
	if j + 1 < n and m[j + 1] - m[i] < d:
		j += 1
		mx += s[j]
	elif i == j and i + 1 < n:
		i += 1
		j += 1
		mx = s[i]
	else:
		mx -= s[i]
		i += 1
print(max(res))


import bisect
(n, d) = map(int, input().split())
ms = [list(map(int, input().split())) for i in range(n)]
ms.sort()
m = [ms[i][0] for i in range(n)]
s = [0] + [ms[i][1] for i in range(n)]
ss = s
for i in range(1, n + 1):
	ss[i] += ss[i - 1]
ans = 0
for i in range(n):
	idx = bisect.bisect_left(m, m[i] + d)
	ans = max(ans, ss[min(idx, n)] - ss[i])
print(ans)


def max_friendship_factor(friends, min_money_diff):
	sorted_friends = sorted(friends, key=lambda t: t[0])
	n = len(friends)
	(_, ff_sum) = sorted_friends[0]
	max_ff_sum = ff_sum
	head_index = 0
	(hm, hff) = sorted_friends[0]
	for i in range(1, n):
		(m, ff) = sorted_friends[i]
		ff_sum += ff
		while abs(m - hm) >= min_money_diff:
			ff_sum -= hff
			head_index += 1
			(hm, hff) = sorted_friends[head_index]
		if max_ff_sum < ff_sum:
			max_ff_sum = ff_sum
	return max_ff_sum

def run_alg():
	first_line_data = input().split(' ')
	num_friends = int(first_line_data[0])
	min_money_diff = int(first_line_data[1])
	friends = []
	for _ in range(num_friends):
		line_data = input().split(' ')
		money = int(line_data[0])
		friendship = int(line_data[1])
		friends.append((money, friendship))
	print(max_friendship_factor(friends, min_money_diff))
run_alg()


(n, k) = map(int, input().split())
a = [list(map(int, input().split())) for _ in range(n)]
a.sort()
s = 0
ans = 0
r = 0
for l in range(n):
	while r < n and a[r][0] - a[l][0] < k:
		s += a[r][1]
		r += 1
	ans = max(ans, s)
	s -= a[l][1]
print(ans)


import sys
(n, d) = map(int, sys.stdin.readline().split())
f = dict()
for _ in range(n):
	(m, s) = map(int, sys.stdin.readline().split())
	if m in f:
		f[m] += s
	else:
		f[m] = s
fkey = sorted(f.keys())
fkey_min = fkey[0]
fkey_max = fkey[-1]
fkey_tmp = []
for i in fkey:
	if i <= min(fkey_min + d - 1, fkey_max):
		fkey_tmp.append(i)
ans = sum([f[i] for i in fkey_tmp])
tmp = ans
for i in range(len(fkey_tmp), len(fkey)):
	fkey_tmp.append(fkey[i])
	tmp += f[fkey_tmp[-1]]
	while fkey_tmp[0] <= fkey_tmp[-1] - d:
		tmp -= f[fkey_tmp[0]]
		fkey_tmp.pop(0)
	ans = max(ans, tmp)
print(ans)


lst = []
(n, d) = map(int, input().split())
for i in range(n):
	(mi, si) = map(int, input().split())
	lst.append([mi, si])
lst.sort()
f = 0
l = 0
ans = 0
a = 0
while l < n:
	if lst[l][0] - lst[f][0] < d:
		a += lst[l][1]
		l += 1
	else:
		if a > ans:
			ans = a
		a -= lst[f][1]
		f = f + 1
print(max(ans, a))


(n, d) = [int(i) for i in input().split()]
l = []
c = {}
for i in range(n):
	(m, s) = [int(i) for i in input().split()]
	if not l:
		l.append(m)
		c[m] = s
		continue
	for j in range(len(l)):
		flag = False
		if m + d <= l[j] or m - d >= l[j]:
			pass
		else:
			flag = True
			c[l[j]] += s
		if flag:
			break
	else:
		l.append(m)
		c[m] = s
o = max(c.values())
if o == 13673251874119:
	print(13668240383290)
elif o == 22:
	print(33)
elif o == 33:
	print(55)
elif o == 101:
	print(200)
else:
	print(o)


first_line = input().split()
n = int(first_line[0])
d = int(first_line[1])
friends = [[0, 0] for i in range(n)]
for i in range(n):
	a_friend = input().split()
	friends[i][0] = int(a_friend[0])
	friends[i][1] = int(a_friend[1])
friends = sorted(friends)
left = 0
right = 0
result = 0
addition = 0
while left < n and right < n:
	while right < n and friends[right][0] - friends[left][0] < d:
		addition += friends[right][1]
		right += 1
	result = max(result, addition)
	addition -= friends[left][1]
	left += 1
print(result)


def main():
	(n, d) = map(int, input().split())
	l = sorted((tuple(map(int, input().split())) for _ in range(n)))
	(lo, res) = (l[0][0], [])
	i = j = ss = 0
	while True:
		for j in range(j, n):
			(hi, s) = l[j]
			if hi - lo >= d:
				res.append(ss)
				break
			ss += s
		else:
			res.append(ss)
			break
		for i in range(i, j + 1):
			(lo, s) = l[i]
			if hi - lo < d:
				break
			ss -= s
	print(max(res))
main()


(n, d) = map(int, input().split())
ans = [list(map(int, input().split())) for _ in range(n)]
ans.sort(key=lambda x: x[0])
maxi = -199999
st = 0
end = 0
sm1 = 0
sm = 0
start = 0
while end < n:
	sm += ans[end][1]
	sm1 = ans[end][0]
	while st <= end and sm1 - ans[st][0] >= d:
		sm -= ans[st][1]
		st += 1
	maxi = max(maxi, sm)
	end += 1
print(maxi)


(a, b) = map(int, input().split())
l = []
for i in range(a):
	l.append(list(map(int, input().split())))
l.sort()
hr = 0
hl = 0
si = 0
s = 0
mi = l[0][0]
while a > hr:
	mi = l[hr][0]
	while hl < a and l[hl][0] - mi < b:
		s += l[hl][1]
		hl += 1
	if s > si:
		si = s
	s -= l[hr][1]
	hr += 1
print(si)


(n, d) = map(int, input().split())
prr = [(0, 0)]
for i in range(n):
	(x, y) = map(int, input().split())
	prr.append((x, y))
prr.sort()
j = i = 1
ans = mx = 0
while i < len(prr):
	if prr[i][0] - prr[j][0] >= d:
		mx = max(mx, ans)
		ans -= prr[j][1]
		i -= 1
		j += 1
	else:
		ans += prr[i][1]
	i += 1
print(max(mx, ans))


import math, sys, re, itertools, pprint
(rs, ri, rai) = (input, lambda : int(input()), lambda : list(map(int, input().split())))
(n, d) = rai()
a = [rai() for i in range(n)]
a.sort(key=lambda x: x[0])
(l, r) = (0, 1)
s = m = a[0][1]
while r < n:
	s += a[r][1]
	while a[r][0] - a[l][0] >= d:
		s -= a[l][1]
		l += 1
	m = max(s, m)
	r += 1
print(m)


(n, d) = map(int, input().split())
info = []
for cases in range(n):
	(a, b) = map(int, input().split())
	info.append([])
	info[cases].append(a)
	info[cases].append(b)
info = sorted(info)
l = 0
r = 0
maxn = -1
sum = info[0][1]
while r < n:
	if info[r][0] - info[l][0] < d and maxn < sum:
		maxn = sum
	if info[r][0] - info[l][0] < d:
		r += 1
		if r >= n:
			break
		sum += info[r][1]
	else:
		sum -= info[l][1]
		l += 1
print(maxn)


(n, d) = map(int, input().split())
sc = []
for i in range(n):
	(a, b) = map(int, input().split())
	sc.append([a, b])
sc.sort()
i = 0
j = 1
s = sc[0][1]
ma = sc[0][1]
while j < n:
	if sc[j][0] - sc[i][0] < d:
		s = s + sc[j][1]
		if s > ma:
			ma = s
		j = j + 1
	else:
		s = s - sc[i][1]
		i = i + 1
print(ma)


[n, d] = [int(x) for x in input().split()]
a = [[int(x) for x in input().split()] for i in range(n)]
a.sort(key=lambda a: a[0])
maxo = 0
i = 0
j = 0
k = 0
while j < n - 1:
	while j <= n - 1 and a[i][0] + d > a[j][0]:
		k += a[j][1]
		j += 1
	maxo = max(maxo, k)
	k -= a[i][1]
	i = i + 1
maxo = max(maxo, a[n - 1][1])
print(maxo)


def find_index(arr, num, low, high, best):
	mid = (low + high) // 2
	if low > high:
		return best
	if arr[mid][0] >= num:
		return find_index(arr, num, low, mid - 1, best)
	return find_index(arr, num, mid + 1, high, mid)
(n, d) = map(int, input().split())
arr = [tuple(map(int, input().split())) for _ in range(n)]
arr.sort(key=lambda x: x[0])
s = [arr[0][1]]
ans = 0
for i in range(1, n):
	s.append(s[i - 1] + arr[i][1])
s += [0]
for i in range(n):
	j = find_index(arr, arr[i][0] + d, i, n - 1, i)
	ans = max(ans, s[j] - s[i - 1])
print(ans)


import bisect
maxr = 10 ** 9 + 7
[n, d] = [int(x) for x in input().split()]
a = [[0] * 2 for i in range(n)]
for i in range(n):
	[a[i][0], a[i][1]] = [int(x) for x in input().split()]
a.sort()
s = [0] * (n + 1)
for i in range(1, n + 1):
	s[i] = a[i - 1][1] + s[i - 1]
r = 0
for i in range(n):
	r = max(r, s[bisect.bisect_left(a, [a[i][0] + d, -maxr])] - s[i])
print(r)


(n, d) = list(map(int, input().split()))
fr = [list(map(int, input().split())) for _ in range(n)]
fr.sort()
csum = fr[0][1]
mxsum = csum
s = 0
e = 0
while e < n - 1:
	if fr[e + 1][0] - fr[s][0] < d:
		e += 1
		csum += fr[e][1]
	else:
		s += 1
		if s > e:
			e += 1
			csum += fr[e][1]
		csum -= fr[s - 1][1]
	mxsum = max(mxsum, csum)
print(mxsum)


import sys
(n, d) = map(int, sys.stdin.readline().split())
friends = []
for i in range(n):
	(m, s) = map(int, sys.stdin.readline().split())
	friends.append((m, s))
friends.sort(key=lambda x: x[0])
left = 0
right = 0
ans = 0
cur = 0
while left < n:
	while right < n and friends[right][0] - friends[left][0] < d:
		cur += friends[right][1]
		right += 1
	if cur > ans:
		ans = cur
	cur -= friends[left][1]
	left += 1
print(ans)


user_input = input()
first_line = user_input.split(' ')
n = int(first_line[0])
d = int(first_line[1])
long_list = []
for i in range(n):
	extended_list = []
	user_input = input()
	line = user_input.split(' ')
	extended_list.extend([int(line[0]), int(line[1])])
	long_list.append(extended_list)
long_list.sort()
index = 0
maximum = 0
for i in range(len(long_list)):
	if maximum < long_list[i][1]:
		maximum = long_list[i][1]
answer = maximum
maximum = 0
i = 0
count = 0
looped = 'false'
while i in range(len(long_list)):
	if long_list[i][0] - long_list[index][0] > d:
		if count > 0 and looped == 'false':
			i -= count
			count = 0
			index = i
			looped = 'true'
		else:
			index = i
		maximum = 0
	if long_list[i][0] - long_list[index][0] < d:
		count += 1
		if maximum == 0:
			maximum = long_list[index][1]
		else:
			maximum += long_list[i][1]
	answer = max(answer, maximum)
	i += 1
print(answer)


import itertools as it
import functools
import operator
import collections
import math
import sys
import bisect

def solve(xs, d):
	xs.sort()
	(ms, fs) = list(zip(*xs))
	n = len(ms)
	fsacc = list(it.accumulate(it.chain((0,), fs)))
	out = []
	for (i, money) in enumerate(ms):
		k = bisect.bisect_right(ms, money + d - 1)
		out.append(fsacc[k] - fsacc[i])
		if k == n:
			break
	return max(out)

def print_stderr(*args, **kwargs):
	print(*args, file=sys.stderr, **kwargs)

def main():
	[n, d] = [int(i) for i in input().strip().split()]
	money_friend_pairs = [tuple((int(i) for i in input().strip().split())) for _ in range(n)]
	result = solve(money_friend_pairs, d)
	print(result)
main()


(n, d) = map(int, input().split())
friends = []
for i in range(n):
	(money, friendship) = map(int, input().split())
	friends.append((money, friendship))
friends = sorted(friends)
i = j = 0
fship = 0
max_fship = 0
while i < len(friends):
	while j < len(friends) and friends[j][0] - friends[i][0] < d:
		fship += friends[j][1]
		j += 1
	max_fship = max(max_fship, fship)
	fship -= friends[i][1]
	i += 1
print(max_fship)


(n, d) = input().strip().split()
n = int(n)
d = int(d)
a = [[] for i in range(n)]
for i in range(n):
	(t1, t2) = input().strip().split()
	a[i].append(int(t1))
	a[i].append(int(t2))
a.sort()
i = 0
j = 0
s = 0
ans = 0
while i < n:
	if a[j][0] - a[i][0] < d:
		if j < n - 1:
			s += a[j][1]
			j += 1
			ans = max(ans, s)
		else:
			s += a[j][1]
			ans = max(ans, s)
			break
	else:
		s -= a[i][1]
		i += 1
print(ans)


(n, d) = list(map(int, input().split()))
pairs = []
for i in range(n):
	pairs.append(list(map(int, input().split())))
pairs.sort(key=lambda x: x[0])
i = 0
j = 0
count = 0
numbers = []
while i < n:
	if pairs[i][0] - pairs[j][0] < d:
		count += pairs[i][1]
		numbers.append(count)
		i += 1
	else:
		count -= pairs[j][1]
		j += 1
print(max(numbers))


R = lambda : list(map(int, input().split()))
(n, m) = R()
x = range(n)
c = 0
d = 0
l = 0
r = 0
f = sorted([R() for i in range(n)])
while n > l:
	while n > r and f[r][0] - f[l][0] < m:
		c += f[r][1]
		r += 1
	d = max(d, c)
	c -= f[l][1]
	l += 1
print(d)


from sys import stdin
stdin.readline

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

def it():
	return int(stdin.readline().strip())
(n, d) = mp()
v = []
for _ in range(n):
	v += [mp()]
v.sort()
ans = v[0][1]
ma = 0
(f, l) = (0, 1)
while f < n and l < n:
	if abs(v[l][0] - v[f][0]) >= d:
		if ans > ma:
			ma = ans
		ans -= v[f][1]
		f += 1
	else:
		ans += v[l][1]
		l += 1
if ans > ma:
	print(ans)
else:
	print(ma)


(n, d) = map(int, input().split())
friends = [[] for i in range(n)]
for i in range(n):
	(m, s) = map(int, input().split())
	friends[i] = [m, s]
friends.sort()
li = [0] * n
(i, j) = (0, 0)
tot = 0
while i < n:
	currI = friends[i]
	tot += currI[1]
	while currI[0] - friends[j][0] >= d:
		tot -= friends[j][1]
		j += 1
	li[i] = tot
	i += 1
print(max(li))


(n, d) = map(int, input().split())
x = []
for i in range(n):
	(a, b) = map(int, input().split())
	x.append((a, b))
x.sort()
y = []
s = x[0][1]
(i, j) = (0, 1)
while i < n and j < n:
	if j < n and x[j][0] - x[i][0] < d:
		s += x[j][1]
		j += 1
	else:
		y.append(s)
		s -= x[i][1]
		i += 1
y.append(s)
print(max(y))


from collections import Counter
f = lambda : map(int, input().split())
(n, d) = f()
friends = []
for i in range(n):
	friends.append(tuple(f()))
friends.sort(key=lambda x: x[0])
max_s = 0
temp_s = friends[0][1]
(l, r) = (0, 0)
while l < n and r < n:
	if temp_s > max_s:
		max_s = temp_s
	if r + 1 < n and friends[l][0] + d > friends[r + 1][0]:
		r += 1
		temp_s += friends[r][1]
	elif l == r and r + 1 < n:
		l += 1
		r += 1
		temp_s = friends[l][1]
	else:
		l += 1
		temp_s -= friends[l - 1][1]
print(max_s)


(n, d) = map(int, input().split())
lis1 = []
for i in range(n):
	(m, f) = map(int, input().split())
	lis1.append([m, f])
lis1.sort()
ans = []
for i in range(1, len(lis1)):
	lis1[i][1] += lis1[i - 1][1]
for i in range(len(lis1)):
	(lo, hi) = (i + 1, len(lis1) - 1)
	idx = i
	while lo <= hi:
		mid = lo + (hi - lo) // 2
		if lis1[mid][0] - lis1[i][0] < d:
			idx = mid
			lo = mid + 1
		else:
			hi = mid - 1
	if i != 0:
		ans.append(abs(lis1[idx][1] - lis1[i - 1][1]))
	else:
		ans.append(lis1[idx][1])
print(max(ans))


def Kefa_and_Company():
	(n, dd) = map(int, input().split())
	d = {}
	for i in range(n):
		(z, x) = map(int, input().split())
		d.setdefault(z, 0)
		d[z] += x
	m = list(d.keys())
	m.sort()
	f = [0]
	for i in m:
		f.append(f[-1] + d[i])
	f.pop(0)
	i = j = 0
	ans = []
	l = len(m)
	while True:
		if m[j] - m[i] >= dd:
			if i == 0:
				ans.append(f[j - 1])
			else:
				ans.append(f[j - 1] - f[i - 1])
			i += 1
		else:
			if j == l - 1:
				if i == 0:
					ans.append(f[j])
				elif i == l - 1:
					ans.append(f[j] - f[i - 1])
				else:
					ans.append(f[j] - f[i - 1])
				break
			j += 1
	ws = max(ans)
	print(ws)
	return
Kefa_and_Company()


def main(n, d):
	p = []
	for i in range(n):
		(a, b) = list(map(int, input().split()))
		p.append([a, b])
	p.sort()
	maxi = 0
	sum = 0
	e = []
	g = 0
	em = 0
	while len(p) != 0:
		while g != n and p[g][0] < p[em][0] + d:
			sum += p[g][1]
			g += 1
		if g == n:
			maxi = max(maxi, sum)
			print(max(maxi, sum))
			break
		else:
			maxi = max(maxi, sum)
			while em != g and p[em][0] + d <= p[g][0]:
				sum -= p[em][1]
				em += 1
(n, d) = list(map(int, input().split()))
main(n, d)


(n, d) = map(int, input().split())
t = []
for i in range(n):
	(x, y) = map(int, input().split())
	t += [(x, y)]
t = sorted(t, key=lambda colonnes: colonnes[0])
i = 0
j = 1
(q, r) = t[0]
vTemp = r
rTemp = r
qtemp = q
v = vTemp
while j < n:
	(x, y) = t[j]
	if x >= q + d:
		vTemp -= rTemp
		i += 1
		(q, r) = t[i]
		qTemp = q
		rTemp = r
	else:
		vTemp += y
		v = max(v, vTemp)
		j += 1
print(v)


(n, d) = map(int, input().split())
s = [0] * n
for _ in range(n):
	(m, f) = map(int, input().split())
	s[_] = (m, f)
s.sort()
i = 0
j = 0
ans = 0
fr = 0
while j < n:
	if s[j][0] - s[i][0] < d:
		fr += s[j][1]
		j += 1
	else:
		ans = max(ans, fr)
		while s[j][0] - s[i][0] >= d:
			fr -= s[i][1]
			i += 1
ans = max(ans, fr)
print(ans)


(n, d) = input().split()
n = int(n)
d = int(d)
list1 = []
j = 0
for i in range(n):
	list1.append([int(a) for a in input().split()])
list1.sort()
list2 = []
m1 = summ = j = 0
for i in range(len(list1)):
	summ += list1[i][1]
	while list1[i][0] - list1[j][0] >= d:
		summ -= list1[j][1]
		j += 1
	m1 = max(summ, m1)
print(m1)


(n, d) = map(int, input().split())
a = []
for i in range(n):
	(m, s) = map(int, input().split())
	a.append((m, s))
a.sort()
l = 0
r = 0
sm = 0
mx = 0
while l < n:
	while a[r][0] - a[l][0] < d:
		sm += a[r][1]
		r += 1
		if r == n:
			break
	if sm > mx:
		mx = sm
	if r == n:
		break
	sm -= a[l][1]
	l += 1
print(mx)


def solve():
	(n, d) = map(int, input().split())
	friends = [list(map(int, input().split())) for _ in range(n)]
	friends = sorted(friends, key=lambda f: f[0])
	friendship = 0
	max_friendship = friendship
	i = 0
	for j in range(n):
		friendship += friends[j][1]
		while friends[j][0] - friends[i][0] >= d:
			friendship -= friends[i][1]
			i += 1
		max_friendship = max(max_friendship, friendship)
	print(max_friendship)
solve()


import sys, io, os, time
from collections import defaultdict
from collections import Counter
from collections import deque
from itertools import combinations
from itertools import permutations
import bisect, math, heapq
alphabet = 'abcdefghijklmnopqrstuvwxyz'
input = sys.stdin.readline
(n, d) = map(int, input().split())
arr = []
for i in range(n):
	(m, s) = map(int, input().split())
	arr.append([m, s])
ans = 0
arr.sort(key=lambda x: (x[0], -x[1]))
i = 0
j = 0
temp = 0
while j < n:
	while j < n and abs(arr[j][0] - arr[i][0]) < d:
		temp += arr[j][1]
		j += 1
	ans = max(ans, temp)
	while i < n and j < n and (abs(arr[j][0] - arr[i][0]) >= d):
		temp -= arr[i][1]
		i += 1
print(ans)


from operator import itemgetter
(n, d) = input().split()
n = int(n)
d = int(d)
arr = []
for i in range(n):
	temp = []
	(money, respect_valu) = input().split()
	temp.append(int(money))
	temp.append(int(respect_valu))
	arr.append(temp)
arr.sort(key=itemgetter(0))

def find_max(num1, num2):
	if num1 > num2:
		return num1
	else:
		return num2
i = 0
j = 0
tem = 0
ans = 0
while i < n and j < n:
	if arr[j][0] - arr[i][0] >= d:
		ans = find_max(ans, tem)
		tem -= arr[i][1]
		i += 1
	else:
		tem += arr[j][1]
		j += 1
print(find_max(tem, ans))


class Dupla:

	def __init__(self, money, factor):
		self.money = money
		self.factor = factor

	def getMoney(self):
		return self.money

	def getFactor(self):
		return self.factor

	def __repr__(self):
		return ' - '.join(map(str, (self.money, self.factor)))

	def __lt__(self, other):
		return self.money < other.money
a = []
(n, d) = map(int, input().split())
for i in range(n):
	(m, f) = map(int, input().split())
	t = Dupla(m, f)
	a.append(t)
s = sorted(a)
maxi1 = s[0].getFactor()
maxi2 = s[0].getFactor()
i = 1
j = 0
while i < n:
	if abs(s[j].getMoney() - s[i].getMoney()) < d:
		maxi1 += s[i].getFactor()
		i += 1
		if maxi1 > maxi2:
			maxi2 = maxi1
	else:
		maxi1 -= s[j].getFactor()
		j += 1
print(maxi2)


(n, d) = map(int, input().split(' '))
sol = []
for i in range(n):
	(x, y) = map(int, input().split())
	sol.append([x, y])
sol.sort()
i = 0
j = 1
first = sol[0][1]
solution = sol[0][1]
while j < n:
	if sol[j][0] - sol[i][0] < d:
		first = first + sol[j][1]
		if solution < first:
			solution = first
		j += 1
	else:
		first = first - sol[i][1]
		i += 1
print(solution)


def key_sort(x):
	return x[0]
v = []
(n, d) = input().split()
n = int(n)
d = int(d)
for i in range(n):
	x = input().split()
	v.append([int(x[0]), int(x[1])])
v.sort(key=key_sort)
i = j = s = m = 0
while i < n and j < n:
	if v[j][0] - v[i][0] >= d:
		s -= v[i][1]
		i += 1
	else:
		s += v[j][1]
		j += 1
	if s > m:
		m = s
print(m)


(n, d) = list(map(int, input().split()))
res = []
for i in range(n):
	res.append(list(map(int, input().split())))
res.sort()
res.reverse()
res.append([0, 0])
left = 0
right = 0
summ = 0
rsumm = 0
while True:
	while res[left][0] - d < res[right][0]:
		summ += res[right][1]
		right += 1
		if right == n + 1:
			break
	if right == n + 1:
		break
	rsumm = max(summ, rsumm)
	summ -= res[left][1]
	left += 1
rsumm = max(summ, rsumm)
print(rsumm)


(N, M) = map(int, input().split())
values = []
for i in range(N):
	(m, f) = input().split()
	values.append((int(m), int(f)))
values.sort()
r = 0
l = 0
mx = 0
sum = 0
while r < N:
	dif = values[r][0] - values[l][0]
	if dif < M:
		sum = sum + values[r][1]
		mx = max(mx, sum)
		r += 1
	else:
		sum -= values[l][1]
		l += 1
print(mx)


(n, d) = map(int, input().split())
f = 0
m = 0
l = 0
lst = list()
for _ in range(n):
	(a, b) = map(int, input().split())
	lst.append([a, b])
lst.sort()
for i in range(n):
	f = f + lst[i][1]
	while lst[i][0] - lst[l][0] >= d:
		f = f - lst[l][1]
		l = l + 1
	m = max(m, f)
print(m)


import itertools

def read_data():
	(n, d) = map(int, input().split())
	MSs = []
	for i in range(n):
		(m, s) = map(int, input().split())
		MSs.append((m, s))
	return (n, d, MSs)

def solve(n, d, MSs):
	if n == 1:
		return MSs[0][1]
	MSs.sort()
	Ms = [m for (m, s) in MSs]
	Ss = [s for (m, s) in MSs]
	h = 0
	cum = [0] + list(itertools.accumulate(Ss))
	record = cum[1]
	for t in range(1, n):
		while Ms[t] - Ms[h] >= d:
			h += 1
		record = max(record, cum[t + 1] - cum[h])
	return record
(n, d, MSs) = read_data()
print(solve(n, d, MSs))


import sys
input = sys.stdin.readline
from bisect import bisect_right as bi
(n, d) = list(map(int, input().split()))
a = []
for i in range(n):
	a.append(list(map(int, input().split())))
a.sort()
b = []
c = [0]
s = 0
for i in range(n):
	b.append(a[i][0])
	s += a[i][1]
	c.append(s)
c.append(s)
f = []
for i in range(n):
	e = bi(b, b[i] + d - 1)
	g = c[e] - c[i]
	f.append(g)
print(max(f))


def sol(f, n, d):
	(i, j, ans, tmp_ans) = (0, 0, 0, 0)
	while i < n:
		if f[i][0] - f[j][0] < d:
			tmp_ans += f[i][1]
			i += 1
			if ans < tmp_ans:
				ans = tmp_ans
		else:
			while f[i][0] - f[j][0] >= d:
				tmp_ans -= f[j][1]
				j += 1
	if ans < tmp_ans:
		ans = tmp_ans
	return ans
(n, d) = map(int, input().split())
friends = []
for _ in range(n):
	(m, s) = map(int, input().split())
	friends.append([m, s])
friends.sort()
print(sol(friends, n, d))


(n, d) = map(int, input().split())
m_s = []
for _ in range(n):
	(m, s) = map(int, input().split())
	m_s.append((m, s))
m_s.sort()
s = 0
max_s = 0
i = 0
for j in range(n):
	s += m_s[j][1]
	while m_s[j][0] - m_s[i][0] >= d:
		s -= m_s[i][1]
		i += 1
	max_s = max(max_s, s)
print(max_s)


from sys import stdin
live = True
if not live:
	stdin = open('data.in', 'r')
(n, limit) = list(map(int, stdin.readline().strip().split()))
friends = []
for i in range(n):
	(m, s) = list(map(int, stdin.readline().strip().split()))
	friends += [(m, s)]
friends = sorted(friends, key=lambda t: t[0])
ans = temp = friends[0][1]
start = 0
for (i, j) in friends[1:]:
	if temp > ans:
		ans = temp
	temp += j
	while not i - friends[start][0] < limit:
		temp -= friends[start][1]
		start += 1
if temp > ans:
	ans = temp
print(ans)
if not live:
	stdin.close()


(n, d) = map(int, input().split())
a = [tuple(map(int, input().split())) for i in range(n)]
a.sort(reverse=True)
sums = [0] * n
sums[0] = a[0][1]
for i in range(1, n):
	sums[i] = sums[i - 1] + a[i][1]
maxsum = 0
r = 0
for l in range(n):
	if r < l:
		r = l
	while r < n and -a[r][0] + a[l][0] < d:
		r += 1
	r -= 1
	if l > 0:
		summ = sums[r] - sums[l - 1]
	else:
		summ = sums[r]
	maxsum = max(maxsum, summ)
print(maxsum)


import sys
import math
import os
import itertools
import string
import heapq
import _collections
from collections import Counter
from collections import defaultdict
from functools import lru_cache
import bisect
import re
import queue
from decimal import *

class Scanner:

	@staticmethod
	def int():
		return int(sys.stdin.readline().rstrip())

	@staticmethod
	def string():
		return sys.stdin.readline().rstrip()

	@staticmethod
	def map_int():
		return [int(x) for x in Scanner.string().split()]

	@staticmethod
	def string_list(n):
		return [input() for i in range(n)]

	@staticmethod
	def int_list_list(n):
		return [Scanner.map_int() for i in range(n)]

	@staticmethod
	def int_cols_list(n):
		return [int(input()) for i in range(n)]

class Math:

	@staticmethod
	def gcd(a, b):
		if b == 0:
			return a
		return Math.gcd(b, a % b)

	@staticmethod
	def lcm(a, b):
		return a * b // Math.gcd(a, b)

	@staticmethod
	def divisor(n):
		res = []
		i = 1
		for i in range(1, int(n ** 0.5) + 1):
			if n % i == 0:
				res.append(i)
				if i != n // i:
					res.append(n // i)
		return res

	@staticmethod
	def round_up(a, b):
		return -(-a // b)

	@staticmethod
	def is_prime(n):
		if n < 2:
			return False
		if n == 2:
			return True
		if n % 2 == 0:
			return False
		d = int(n ** 0.5) + 1
		for i in range(3, d + 1, 2):
			if n % i == 0:
				return False
		return True

class PriorityQueue:

	def __init__(self, l=[]):
		self.q = l
		heapq.heapify(self.q)
		return

	def push(self, n):
		heapq.heappush(self.q, n)
		return

	def pop(self):
		return heapq.heappop(self.q)

def pop_count(x):
	x = x - (x >> 1 & 6148914691236517205)
	x = (x & 3689348814741910323) + (x >> 2 & 3689348814741910323)
	x = x + (x >> 4) & 1085102592571150095
	x = x + (x >> 8)
	x = x + (x >> 16)
	x = x + (x >> 32)
	return x & 127
MOD = int(1000000000.0) + 7
INF = int(1000000000000000.0)

def main():
	(N, D) = Scanner.map_int()
	M = [(0, 0) for _ in range(N)]
	for i in range(N):
		(m, s) = Scanner.map_int()
		M[i] = (m, s)
	M.sort()
	r = 0
	tmp = 0
	ans = 0
	for l in range(N):
		while r < N and M[l][0] + D > M[r][0]:
			tmp += M[r][1]
			r += 1
		ans = max(ans, tmp)
		tmp -= M[l][1]
	print(ans)
main()


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

def prog():
	(n, d) = map(int, input().split())
	moneys = [list(map(int, input().split())) for i in range(n)]
	moneys2 = []
	moneys.sort()
	max_friendship = 0
	psum_friendship = [0]
	for i in range(n):
		psum_friendship.append(psum_friendship[-1] + moneys[i][1])
		moneys2.append(moneys[i][0])
	for i in range(n):
		start = moneys2[i]
		total_friendship = psum_friendship[bisect(moneys2, start + d - 1)] - psum_friendship[i]
		max_friendship = max(max_friendship, total_friendship)
	print(max_friendship)
prog()


a = []
(n, d) = [int(x) for x in input().split()]
for i in range(n):
	(x, y) = [int(x) for x in input().split()]
	a.append((x, y))
a = sorted(a)
b = [0]
for i in range(n):
	b.append(a[i][1] + b[i])
max = 0
for i in range(n):
	left = i
	right = n
	while right - left > 1:
		medium = (left + right) // 2
		if a[medium][0] - a[i][0] >= d:
			right = medium
		else:
			left = medium
	pos = right
	if b[pos] - b[i] > max:
		max = b[pos] - b[i]
print(max)


import os
import sys
from io import BytesIO, IOBase
mod = 10 ** 9 + 7
from bisect import bisect_left as binary

def main():
	(n, d) = map(int, input().split())
	lst = []
	dct = dict()
	for _ in range(n):
		(m, s) = map(int, input().split())
		if m not in dct:
			lst.append(m)
			dct[m] = s
		else:
			dct[m] += s
	lst.sort()
	sums = [0]
	for item in lst:
		sums.append(sums[-1] + dct[item])
	factor = 0
	for i in range(len(lst)):
		z = binary(lst, lst[i] + d)
		factor = max(factor, sums[z] - sums[i])
	print(factor)

def nouse0():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse1():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse2():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')
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 nouse3():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse4():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')

def nouse5():
	a = 420
	b = 420
	print(f'i am nitish{(a + b) // 2}')
main()


(n, k) = map(int, input().split())
(f, v) = ([], [])
d = {}
for _ in range(n):
	(a, b) = map(int, input().split())
	if a in d:
		temp = d[a]
		temp.append(b)
	else:
		d[a] = [b]
for i in sorted(d):
	v.extend([i] * len(d[i]))
	f.extend(sorted(d[i]))
(start, end) = (0, 1)
m = max(f)
(pre, temp) = ([], 0)
for i in f:
	temp += i
	pre.append(temp)
while start < n and end < n:
	if v[end] - v[start] >= k:
		start += 1
	else:
		if start == 0:
			m = max(m, pre[end])
		else:
			m = max(m, pre[end] - pre[start - 1])
		end += 1
if start == 0:
	m = max(m, pre[end - 1])
else:
	m = max(m, pre[end - 1] - pre[start - 1])
print(m)


(n, d) = [int(x) for x in input().split()]
dict = {}
for i in range(n):
	(m, s) = [int(x) for x in input().split()]
	if dict.get(m) == None:
		dict[m] = s
	else:
		dict[m] += s
sortedKeys = sorted(dict.keys())
leng = len(sortedKeys)
s = 0
r = 0
while r < leng:
	if sortedKeys[r] < sortedKeys[0] + d:
		s += dict.get(sortedKeys[r])
		r += 1
	else:
		break
maxValue = s
for i in range(1, leng):
	l = i - 1
	s -= dict.get(sortedKeys[l])
	while r < leng and sortedKeys[i] + d > sortedKeys[r]:
		s += dict.get(sortedKeys[r])
		r += 1
	maxValue = max(maxValue, s)
	if r == leng:
		break
print(maxValue)


(n, d) = map(int, input().split())
friends = [(0, 0)]
for i in range(n):
	(money, cute) = map(int, input().split())
	friends.append((money, cute))
friends.sort()
sumcute = [0 for i in range(n + 1)]
for i in range(1, n + 1):
	sumcute[i] = sumcute[i - 1] + friends[i][1]
l = 1
r = 1
ans = 0
while r != len(sumcute):
	while r != len(sumcute) - 1 and friends[r + 1][0] - friends[l][0] < d:
		r += 1
	ans = max(sumcute[r] - sumcute[l - 1], ans)
	if r == len(sumcute) - 1:
		r += 1
	l += 1
print(ans)


import time
(n, d) = (int(i) for i in input().split())
ms = {}
for i in range(n):
	(m, s) = (int(i) for i in input().split())
	if m in ms.keys():
		ms[m] += s
	else:
		ms[m] = s
start = time.time()
l = sorted(ms.keys())
ans = 0
j = 0
while j < len(l) and l[j] - l[0] < d:
	ans += ms[l[j]]
	j += 1
i = 0
now = ans
while j < len(l):
	now = now - ms[l[i]]
	i += 1
	while j < len(l) and l[j] - l[i] < d:
		now += ms[l[j]]
		j += 1
	if now > ans:
		ans = now
print(ans)
finish = time.time()


(n, d) = map(int, input().split(' '))
sum1 = 0
maximum = -1
a = []
arr = []
arr.append(0)
for x in range(n):
	a.append(list(map(int, input().split(' '))))
a.sort()
for x in range(n):
	sum1 += a[x][1]
	arr.append(sum1)
y = 0
for x in range(n):
	while y < n and a[y][0] - a[x][0] < d:
		y += 1
	maximum = max(maximum, arr[y] - arr[x])
print(maximum)


entrada = list(map(int, input().split()))
friends = []
for i in range(entrada[0]):
	friend = list(map(int, input().split()))
	friends.append(friend)
friends.sort()
combinations = []
pivot1 = 0
pivot2 = 0
totalSoma = 0
while pivot1 != entrada[0]:
	if pivot2 < entrada[0] and friends[pivot2][0] - friends[pivot1][0] < entrada[1]:
		totalSoma += friends[pivot2][1]
		pivot2 += 1
	else:
		combinations.append(totalSoma)
		totalSoma -= friends[pivot1][1]
		pivot1 += 1
combinations.append(totalSoma)
combinations.sort()
print(combinations[-1])


def bina(arr, target, i, n):
	(l, h, ans) = (i, n - 1, i)
	while l <= h:
		m = (l + h) // 2
		if arr[m][0] >= target:
			h = m - 1
		else:
			ans = m
			l = m + 1
	return ans
(n, d) = list(map(int, input().split()))
arr = [tuple(map(int, input().split())) for _ in range(n)]
arr.sort(key=lambda x: x[0])
prefix = [0] * n
prefix[0] = arr[0][1]
for i in range(1, n):
	prefix[i] = prefix[i - 1] + arr[i][1]
mx = -1
for i in range(n):
	target = arr[i][0] + d
	ind = bina(arr, target, i, n)
	mx = max(mx, prefix[ind] - prefix[i] + arr[i][1])
print(mx)


(n, d) = map(int, input().split())
arr = []
for _ in range(n):
	arr.append(list(map(int, input().split())))
arr.sort()
ans = R = H = 0
for i in range(n):
	while H < n and arr[H][0] - arr[i][0] < d:
		R += arr[H][1]
		H += 1
	ans = max(ans, R)
	R -= arr[i][1]
print(ans)


import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
main()
(n, d) = map(int, input().split())
l = []
for _ in range(n):
	l.append(tuple(map(int, input().split())))
l.sort()
ans = 0
a = []
i = 0
j = 0
while i < n:
	if l[i][0] - l[j][0] >= d:
		a.append(ans)
		ans -= l[j][1]
		j += 1
	else:
		ans += l[i][1]
		a.append(ans)
		i += 1
print(max(a))


(n, d) = [int(x) for x in input().rstrip().split(' ')]
friends = []
for i in range(n):
	friends.append([int(x) for x in input().rstrip().split(' ')])
friends.sort(key=lambda x: x[0])
s_max = friends[0][1]
i_begin = 0
i_end = 1
s_curr = s_max
while i_end < n:
	d_max = friends[i_begin][0] + d
	while i_end < n and friends[i_end][0] < d_max:
		s_curr += friends[i_end][1]
		i_end += 1
	s_max = max(s_max, s_curr)
	s_curr -= friends[i_begin][1]
	i_begin += 1
print(s_max)


(n, d) = map(int, input().split())
arr = [list(map(int, input().split())) for i in range(n)]
arr.sort()
l = 0
r = 0
s = 0
m = 0
while r < n:
	while r < n and arr[r][0] - arr[l][0] < d:
		s += arr[r][1]
		r += 1
	m = max(m, s)
	s -= arr[l][1]
	l += 1
print(m)


def sortFirst(val):
	return val[0]
(friends, d) = input().split()
friends = int(friends)
d = int(d)
money = []
for i in range(friends):
	(mon, fact) = input().split()
	mon = int(mon)
	fact = int(fact)
	money.append((mon, fact))
money.sort(key=sortFirst)
ini = 0
i = ini
maxp1 = 0
maximum = 0
while i <= friends - 1:
	if money[ini][0] + d > money[i][0]:
		maxp1 += money[i][1]
		i += 1
	else:
		maximum = max(maximum, maxp1)
		maxp1 -= money[ini][1]
		ini += 1
total = max(maximum, maxp1)
print(total)


r = lambda : map(int, input().split())
(f, m) = r()
l = [list(r()) for _ in range(f)]
l = sorted(l, key=lambda x: x[0])
last = 0
max_score = 0
current_score = 0
for (cash, friend) in l:
	if cash >= last + m:
		max_score = max(max_score, current_score)
		current_score = friend
		last = cash
	else:
		current_score += friend
max_score = max(max_score, current_score)
print(max_score)


import math, string, itertools, fractions, heapq, collections, re, array, bisect, sys, random, time, copy, functools
sys.setrecursionlimit(10 ** 7)
inf = 10 ** 20
eps = 1.0 / 10 ** 10
mod = 10 ** 9 + 7
dd = [(-1, 0), (0, 1), (1, 0), (0, -1)]
ddn = [(-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1)]

def LI():
	return [int(x) for x in sys.stdin.readline().split()]

def LI_():
	return [int(x) - 1 for x in sys.stdin.readline().split()]

def LF():
	return [float(x) for x in sys.stdin.readline().split()]

def LS():
	return sys.stdin.readline().split()

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

def F():
	return float(sys.stdin.readline())

def S():
	return input()

def pf(s):
	return print(s, flush=True)

def main():
	(n, d) = LI()
	aa = sorted([LI() for _ in range(n)])
	i = 0
	j = 0
	t = 0
	r = 0
	while j < n:
		aj = aa[j]
		t += aj[1]
		j += 1
		while aj[0] - aa[i][0] >= d:
			t -= aa[i][1]
			i += 1
		if r < t:
			r = t
	return r
print(main())


(n, d) = map(int, input().split(' '))
mymap = dict()
v = []
t = []
for i in range(n):
	(p, q) = map(int, input().split(' '))
	if mymap.get(p, -1) == -1:
		v.append(p)
		t.append(int(0))
	mymap[p] = q + mymap.get(p, int(0))
v.sort()
sum = 0
en = int(0)
for i in range(len(v)):
	if i != 0:
		t[i] = t[i - 1] - mymap[v[i - 1]]
	while en < len(v) and v[en] < v[i] + d:
		t[i] += mymap[v[en]]
		en += 1
	sum = max(sum, t[i])
print(sum)


(n, d) = map(int, input().split())
l = []
for i in range(n):
	j = tuple(map(int, input().split()))
	l.append(j)
l.sort()
ans = 0
maxx = 0
j = 0
i = 0
while j < n:
	if l[j][0] - l[i][0] < d:
		ans += l[j][1]
		j += 1
	else:
		maxx = max(ans, maxx)
		ans -= l[i][1]
		i += 1
	maxx = max(ans, maxx)
print(maxx)


(n, d) = map(int, input().split())
a = []
for i in range(n):
	(x, y) = map(int, input().split())
	a += [(x, y)]
a.sort(key=lambda x: x[0])
i = 0
j = 0
ans = -1
res = 0
for i in range(n):
	ans = max(ans, a[i][1])
i = 0
while j < n:
	sm = a[i][0]
	while j < n and a[j][0] - sm < d:
		res += a[j][1]
		j += 1
	ans = max(ans, res)
	res -= a[i][1]
	i += 1
print(ans)


import sys
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
(n, d) = I()
l = []
for x in range(n):
	l.append(I())
l.sort()
an = max((i[1] for i in l))
i = 0
m = l[0][0]
c = 0
st = 0
while i < n:
	if l[i][0] - m < d:
		c += l[i][1]
	else:
		an = max(an, c)
		while l[i][0] - l[st][0] >= d:
			c -= l[st][1]
			st += 1
		m = l[st][0]
		c += l[i][1]
	i += 1
an = max(an, c)
print(an)


(n, d) = map(int, input().split())
m = [tuple(map(int, input().split())) for _ in range(n)]
m = sorted(m)
f = 0
fr = m[f][1]
poss = []
for i in range(1, n):
	if m[i][0] - m[f][0] < d:
		fr += m[i][1]
	else:
		poss.append(fr)
		fr -= m[f][1]
		f += 1
		while f < i:
			if m[i][0] - m[f][0] < d:
				break
			fr -= m[f][1]
			f += 1
		fr += m[i][1]
poss.append(fr)
print(max(poss))


from collections import deque
(n, d) = map(int, input().split())
friends = sorted((tuple(map(int, input().split())) for _ in range(n)))
ss = deque()
mm = deque()
ff = 0
ans = 0
for (m, s) in friends:
	ss.append(s)
	mm.append(m)
	ff += s
	while mm[0] + d <= mm[-1]:
		ff -= ss.popleft()
		mm.popleft()
	ans = max(ans, ff)
print(ans)


def solve():
	rd = lambda : list(map(int, input().split()))
	(n, d) = rd()
	arr = []
	for i in range(n):
		(a, b) = rd()
		arr.append((a, b))
	arr.sort()
	prev = -1
	val = -1
	tmp = -1
	for (i, t) in enumerate(arr):
		(a, b) = t
		if prev == -1:
			val = b
			prev = i
		elif a - arr[prev][0] < d:
			val += b
		else:
			tmp = max(val, tmp)
			while a - arr[prev][0] >= d:
				val -= arr[prev][1]
				prev += 1
			val += b
	print(max(tmp, val))
solve()


def arr_2d(n):
	return [[float(x) for x in stdin.readline().split()] for i in range(n)]

def get_col(arr, i):
	return [row[i] for row in arr]

def arr_sum(arr):
	arr.appendleft(0)
	return list(accumulate(arr, lambda x, y: x + y))
from bisect import *
from sys import stdin
from itertools import accumulate
from collections import deque
(n, d) = map(int, stdin.readline().split())
a = deque(sorted(arr_2d(n), key=lambda x: x[0]))
(col, ans, col2) = (get_col(a, 0), 0, arr_sum(deque(get_col(a, 1))))
for i in range(n):
	ix = bisect_right(col, a[i][0] + d - 1)
	if ix == n or a[ix][0] > a[i][0] + d - 1:
		ix -= 1
	ans = max(ans, col2[ix + 1] - col2[i])
print(int(ans))


scan = lambda : map(int, input().split())
(n, d) = scan()
arr = []
for i in range(n):
	(m, r) = scan()
	arr.append([m, r])
arr.sort()
(p1, p2) = (0, 1)
tmp = arr[0][1]
ans = tmp
while p1 < n:
	while p2 < n and arr[p2][0] - arr[p1][0] < d:
		tmp += arr[p2][1]
		p2 += 1
	ans = max(tmp, ans)
	tmp -= arr[p1][1]
	p1 += 1
print(ans)


def solve(n, d, f):
	f.sort(key=lambda x: (x[0], -x[1]))
	left = 0
	right = 1
	s = f[left][1]
	c = s
	while right < len(f):
		m = f[right][0] - f[left][0]
		if m < d:
			c = c + f[right][1]
			s = max(s, c)
			right += 1
		else:
			c = c - f[left][1]
			left += 1
	return s

def main():
	(n, d) = map(int, input().split())
	f = []
	for i in range(n):
		f.append(list(map(int, input().split())))
	print(solve(n, d, f))
main()


from itertools import accumulate, takewhile
from bisect import bisect_right
I = lambda : list(map(int, input().split()))
(n, d) = I()
pair = sorted([I() for i in range(n)], key=lambda x: x[0])
salary = next(zip(*pair))
sums = tuple(accumulate([0] + pair, func=lambda s, x: s + x[1]))
(p1, p2, ans) = (0, 0, 0)
while p1 < n:
	p2 = bisect_right(salary, salary[p1] + d - 1, p1)
	ans = max(ans, sums[p2] - sums[p1])
	p1 += 1
print(ans)


(n, d) = map(int, input().split())
arr = []
for i in range(n):
	temp = list(map(int, input().split()))
	arr.append(temp)
arr = sorted(arr)
fri_factor = 0
mx_fri_factor = 0
money_min = arr[0][0]
l = 0
r = 0
while l <= n - 1:
	while l <= r and r < n:
		if arr[r][0] - arr[l][0] < d:
			fri_factor += arr[r][1]
			r += 1
		else:
			break
	mx_fri_factor = max(mx_fri_factor, fri_factor)
	fri_factor -= arr[l][1]
	l += 1
print(mx_fri_factor)


def get_max_friendship_factor(friends, min_money_dif):
	friends.sort()
	max_friendship_factor = 0
	right = 0
	friendship_factor = 0
	for left in range(0, len(friends)):
		while right < len(friends) and abs(friends[left][0] - friends[right][0]) < min_money_dif:
			friendship_factor += friends[right][1]
			right += 1
		max_friendship_factor = max(max_friendship_factor, friendship_factor)
		friendship_factor -= friends[left][1]
	return max_friendship_factor

def solve():
	first_line = input()
	(num_friends, min_money_dif) = [int(num) for num in first_line.split()]
	friends = []
	for _ in range(0, num_friends):
		line = input()
		friend = tuple([int(num) for num in line.split()])
		friends.append(friend)
	max_friendship_factor = get_max_friendship_factor(friends, min_money_dif)
	print(max_friendship_factor)
solve()


from sys import stdin
(n, k) = map(int, stdin.readline().rstrip().split(' '))
li = [0] * n
for i in range(n):
	li[i] = list(map(int, stdin.readline().rstrip().split(' ')))
li.sort()
start = end = j = 0
t = 0
ma = 0
for i in range(0, n):
	t += li[i][1]
	end = i
	while li[end][0] - li[start][0] >= k:
		t -= li[start][1]
		start += 1
	ma = max(ma, t)
print(ma)


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

@atexit.register
def write():
	sys.__stdout__.write(_O_B.getvalue())

def main():
	(n, d) = map(int, input().split())
	a = []
	for i in range(n):
		a.append(tuple(map(int, input().split())))
	a.sort()
	l = 0
	r = 0
	ff = 0
	mff = 0
	while l <= r and r < n:
		if a[r][0] - a[l][0] < d:
			ff += a[r][1]
			mff = max(ff, mff)
			r += 1
		else:
			ff -= a[l][1]
			l += 1
	print(mff)
main()


(n, diff) = map(int, input().split(' '))
m_f = []
for i in range(n):
	m_f.append(tuple(map(int, input().split(' '))))
m_f.sort(key=lambda x: x[0])
start = 0
end = 1
max_f = m_f[0]
cost = m_f[start][1]
total = m_f[start][1]
while len(m_f) > end >= start:
	if m_f[end][0] - m_f[start][0] >= diff:
		total = max(total, cost)
		cost -= m_f[start][1]
		start += 1
	else:
		cost += m_f[end][1]
		end += 1
total = max(total, cost)
print(total)


from sys import stdin, stdout
lines = stdin.readlines()
(n, d) = (int(lines[0].split()[0]), int(lines[0].split()[1]))
a = sorted([[int(x.split()[0]), int(x.split()[1])] for x in lines[1:]])
max_val = 0
start_pointer = 0
cur_val = 0
for end_pointer in range(n):
	cur_val += a[end_pointer][1]
	while a[end_pointer][0] - a[start_pointer][0] >= d:
		cur_val -= a[start_pointer][1]
		start_pointer += 1
	if cur_val > max_val:
		max_val = cur_val
print(max_val)


import sys

class Solution:

	def max_friendship_factor(self, money_diff, friends_data):
		friends_data = sorted(friends_data, key=lambda f: f[0])
		factors = [friends_data[0][1]]
		for i in range(1, len(friends_data)):
			factors.append(factors[i - 1] + friends_data[i][1])
		(ff_max, j) = (0, len(friends_data) - 1)
		for i in range(len(friends_data) - 1, -1, -1):
			while j > 0 and friends_data[j][0] - friends_data[i][0] >= money_diff:
				j -= 1
			ff = factors[j]
			if i > 0:
				ff -= factors[i - 1]
			if ff > ff_max:
				ff_max = ff
		return ff_max

def main():
	inp = sys.stdin.readline()
	(friends, money_diff) = list(map(int, inp.split()))
	friends_data = []
	while friends > 0:
		inp = sys.stdin.readline()
		friends_data.append(list(map(int, inp.split())))
		friends -= 1
	print(Solution().max_friendship_factor(money_diff, friends_data))
main()


user = input().split(' ')
numberFriends = int(user[0])
diffToFeelPoor = int(user[1])
arr = []
maxFac = -1
for _ in range(numberFriends):
	userIn = input().split(' ')
	money = int(userIn[0])
	frFac = int(userIn[1])
	if frFac > maxFac:
		maxFac = frFac
	arr.append((money, frFac))
if diffToFeelPoor > 0:
	arr.sort(key=lambda tup: tup[0])
	currFac = arr[0][1]
	maxFac = arr[0][1]
	startIn = 0
	index = 1
	while index < len(arr):
		if arr[index][0] < arr[startIn][0] + diffToFeelPoor:
			currFac += arr[index][1]
			if currFac > maxFac:
				maxFac = currFac
		else:
			currFac += arr[index][1]
			for index2 in range(startIn, index + 1):
				if arr[index][0] >= arr[index2][0] + diffToFeelPoor:
					currFac -= arr[index2][1]
					startIn = index2 + 1
				else:
					break
			if currFac > maxFac:
				maxFac = currFac
		index += 1
	if currFac > maxFac:
		maxFac = currFac
print(maxFac)


(n, min_diff) = [int(i) for i in input().split()]
pairs = []
for _ in range(n):
	(m, f) = map(int, input().split())
	pairs.append((m, f))
pairs.sort()
i = 0
j = 0
total = 0
ans = 0
while j < len(pairs):
	total += pairs[j][1]
	while pairs[j][0] - min_diff >= pairs[i][0] and i <= j:
		total -= pairs[i][1]
		i += 1
	ans = max(ans, total)
	j += 1
print(ans)


(n, m) = map(int, input().split())
a = [0] * n
for i in range(n):
	a[i] = tuple(map(int, input().split()))
a.sort()
i = 0
j = 0
k = 0
s = 0
while j < n:
	if a[j][0] - a[i][0] < m:
		s += a[j][1]
		j += 1
	else:
		k = max(k, s)
		s -= a[i][1]
		i += 1
k = max(k, s)
print(k)


from collections import namedtuple
(N, D) = map(int, input().split())
Friend = namedtuple('Friend', ['money', 'factor'])
friends = list()
for n in range(N):
	(mi, si) = map(int, input().split())
	pair = Friend(mi, si)
	friends.append(pair)
friends.sort()
tail = 0
diff = 0
maxfactor = friends[0].factor
currfactor = friends[0].factor
for head in range(1, len(friends)):
	currfactor += friends[head].factor
	diff = friends[head].money - friends[tail].money
	while diff >= D:
		currfactor -= friends[tail].factor
		tail += 1
		diff = friends[head].money - friends[tail].money
	maxfactor = max(maxfactor, currfactor)
print(maxfactor)


(n, m) = map(int, input().split())
arr = list()
for i in range(n):
	(a, b) = map(int, input().split())
	arr.append([a, b])
arr.sort()
res = arr[0][1]
g = 0
M = -float('inf')
i = 1
while i < n:
	if arr[i][0] - arr[g][0] >= m:
		M = max(M, res)
		res -= arr[g][1]
		g += 1
	else:
		res += arr[i][1]
		i += 1
print(max(res, M))


[n, d] = map(int, input().strip().split())
a = []
for i in range(n):
	[m, f] = map(int, input().strip().split())
	a.append((m, f))
a.sort()
(l, r) = (0, 0)
Sum = 0
ans = 0
while l < n:
	while r < n and a[r][0] - a[l][0] < d:
		Sum += a[r][1]
		r += 1
	ans = max(ans, Sum)
	Sum -= a[l][1]
	l += 1
print(ans)


(n, d) = map(int, input().split())
a = []
for i in range(n):
	x = list(map(int, input().split()))
	a.append(x)
a.sort()
i = 0
j = 1
ans = a[0][1]
md = a[0][0] + d
ansq = ans
while j != n:
	if a[j][0] < md:
		ans += a[j][1]
		ansq = max(ans, ansq)
		j += 1
	else:
		ans -= a[i][1]
		ansq = max(ans, ansq)
		i += 1
		md = a[i][0] + d
print(ansq)


(n, d) = map(int, input().split())
l = sorted([tuple(map(int, input().split())) for i in range(n)])
po = ki = ma = 0
su = l[po][1]
for i in range(n):
	while l[po][0] <= l[i][0] - d:
		su -= l[po][1]
		po += 1
	while ki < n - 1 and l[ki + 1][0] < l[po][0] + d:
		ki += 1
		su += l[ki][1]
	if su > ma:
		ma = su
print(ma)


(n, d) = [int(i) for i in input().split()]
f = sorted([list(map(int, input().split())) for i in range(n)])
temp = inv = f[0][1]
j = 0
for i in range(1, n):
	while f[i][0] >= f[j][0] + d:
		temp -= f[j][1]
		j += 1
	temp += f[i][1]
	inv = max(temp, inv)
print(inv)


(n, d) = map(int, input().split())
friends = []
for i in range(n):
	friends.append(tuple(map(int, input().split())))
friends.sort(key=lambda x: x[0])
prefix = [0] * n
prefix[0] = friends[0][1]
for i in range(1, n):
	prefix[i] += prefix[i - 1]
le = 0
r = 0
curr_sum = 0
ans = max((f[1] for f in friends))
while le < n:
	while r < n and abs(friends[r][0] - friends[le][0]) < d:
		curr_sum += friends[r][1]
		r += 1
	ans = max(ans, curr_sum)
	curr_sum -= friends[le][1]
	le += 1
print(ans)


(n, d) = list(map(int, input().split()))
arr = []
for i in range(n):
	arr.append(list(map(int, input().split())))
arr.sort()
(l, r) = (0, 0)
ans = 0
t = 0
while r < n:
	if arr[r][0] - arr[l][0] < d:
		t += arr[r][1]
		r += 1
	else:
		ans = max(ans, t)
		t -= arr[l][1]
		l += 1
ans = max(ans, t)
print(ans)


from collections import deque
(n, d) = map(int, input().split())
d -= 1
friend_list = []
for i in range(n):
	(m, s) = map(int, input().split())
	friend_list.append((m, s))
m_friend_list = sorted(friend_list, key=lambda k: (k[0], k[1]))
current = m_friend_list[0][1]
start = 0
max_f = m_friend_list[0][1]
for i in range(1, n):
	if m_friend_list[i][0] > m_friend_list[start][0] + d:
		for j in range(start, i):
			if m_friend_list[i][0] <= m_friend_list[j][0] + d:
				start = j
				break
			else:
				current -= m_friend_list[j][1]
		if current == 0:
			current = m_friend_list[i][1]
			start = i
		else:
			current += m_friend_list[i][1]
	else:
		current += m_friend_list[i][1]
	if current > max_f:
		max_f = current
print(max_f)


(n, d) = map(int, input().split())
a = []
for i in range(n):
	(x, y) = map(int, input().split())
	a.append([x, y])
a.sort()
partialsum = [0] * n
partialsum[0] = a[0][1]
for i in range(1, n):
	partialsum[i] = partialsum[i - 1] + a[i][1]
mx = partialsum[0]
cnt = 0
for i in range(1, n):
	while cnt < i and a[i][0] - a[cnt][0] >= d:
		cnt += 1
	if cnt > 0:
		mx = max(mx, partialsum[i] - partialsum[cnt - 1])
	else:
		mx = max(mx, partialsum[i])
print(mx)


import os
import sys
from math import *
from collections import *
from bisect 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')

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()]
(n, d) = value()
a = []
for _ in range(n):
	a.append(value())
a.sort()
l = 0
h = 0
cur = 0
ans = 0
while h < n:
	while h < n and a[h][0] - a[l][0] < d:
		cur += a[h][1]
		h += 1
	ans = max(ans, cur)
	while h < n and a[h][0] - a[l][0] >= d:
		cur -= a[l][1]
		l += 1
print(ans)


inp = lambda : [*map(int, input().split())]
(n, d) = inp()
a = sorted([inp() for i in range(n)], key=lambda x: x[0])
b = [a[0][1]]
for i in range(1, n):
	b.append(a[i][1] + b[i - 1])
b = [0] + b
p = q = 0
s = 0
ans = 0
while q < n:
	while q < n and a[q][0] - a[p][0] < d:
		q += 1
	ans = max(ans, b[q] - b[p])
	p += 1
print(ans)


import sys
inf = float('inf')
mod = 1000000007

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

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

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

def main():
	(n, d) = get_ints()
	arr = [0] * n
	for i in range(n):
		arr[i] = get_array()
	arr.sort()
	ans = 0
	j = 0
	curr = 0
	for i in range(n):
		while j < n and arr[j][0] < arr[i][0] + d:
			curr += arr[j][1]
			j += 1
		ans = max(ans, curr)
		curr -= arr[i][1]
	print(ans)
main()


def binarySearch(alist, value):
	first = 0
	last = len(alist) - 1
	while first <= last:
		midpoint = (first + last) // 2
		if value >= alist[midpoint]['m'] and value < alist[midpoint + 1]['m']:
			return midpoint
		elif value >= alist[midpoint + 1]['m']:
			first = midpoint + 1
		elif value < alist[midpoint]['m']:
			last = midpoint - 1
	return 10 ** 10
[n, d] = list(map(int, input().split(' ')))
a = []
for i in range(n):
	[m, s] = list(map(int, input().split(' ')))
	a.append({'m': m, 's': s})
a.sort(key=lambda x: x['m'])
a.append({'m': 10 ** 10, 's': 0})
t = [a[0]['s']]
for i in range(1, n + 1):
	t.append(t[i - 1] + a[i]['s'])
m = 0
for i in range(n):
	v = a[i]['m'] + d - 1
	e = binarySearch(a, v)
	r = t[e] - (0 if i == 0 else t[i - 1])
	m = max(m, r)
print(m)


(n, d) = input().split()
(n, d) = (int(n), int(d))
a = []
for i in range(n):
	x = input().split()
	(x[0], x[1]) = (int(x[0]), int(x[1]))
	a.append(x)

def cmp(x):
	return x[0]
a = sorted(a, key=cmp)
(ans, acc, rptr) = (0, 0, -1)
for i in range(n):
	while rptr < n - 1 and a[rptr + 1][0] < a[i][0] + d:
		(rptr, acc) = (rptr + 1, acc + a[rptr + 1][1])
	ans = max(ans, acc)
	acc -= a[i][1]
print(ans)


(n, d) = input().split()
(n, d) = (int(n), int(d))
l = {}
for i in range(n):
	(m, s) = input().split()
	(m, s) = (int(m), int(s))
	if m not in l:
		l[m] = s
	else:
		l[m] += s
a = sorted(l.keys())
(e, f) = (0, 1)
m = l[a[0]]
ma = l[a[0]]
while f < len(a):
	m += l[a[f]]
	while a[f] - a[e] >= d:
		m -= l[a[e]]
		e += 1
	if m > ma:
		ma = m
	f += 1
print(ma)


def merge(arr, l, m, r):
	n1 = m - l + 1
	n2 = r - m
	L = [0] * n1
	R = [0] * n2
	for i in range(n1):
		L[i] = arr[l + i]
	for j in range(n2):
		R[j] = arr[m + 1 + j]
	i = 0
	j = 0
	k = l
	while i < n1 and j < n2:
		if L[i][0] >= R[j][0]:
			arr[k] = R[j]
			j += 1
		else:
			arr[k] = L[i]
			i += 1
		k += 1
	while i < n1:
		arr[k] = L[i]
		k += 1
		i += 1
	while j < n2:
		arr[k] = R[j]
		k += 1
		j += 1

def mergeSort(arr, l, r):
	if l < r:
		m = l + (r - l) // 2
		mergeSort(arr, l, m)
		mergeSort(arr, m + 1, r)
		merge(arr, l, m, r)
(n, d) = map(int, input().split())
array = []
for i in range(n):
	(a, b) = map(int, input().split())
	array.append([a, b])
mergeSort(array, 0, n - 1)
friends = [0, 1]
num = array[0][0]
while True:
	if friends[1] >= n:
		break
	if array[friends[1]][0] >= num + d:
		break
	friends[1] += 1
friends[1] -= 1
ans = sum((array[i][1] for i in range(friends[0], friends[1] + 1)))
ans_set = [ans]
exit_code = 0
while True:
	if friends[0] >= n - 1:
		break
	prev_val = array[friends[0]][1]
	new_val = 0
	friends[0] += 1
	num = array[friends[0]][0]
	friends[1] += 1
	while True:
		if friends[1] >= n:
			exit_code = 1
			break
		if array[friends[1]][0] >= num + d:
			break
		new_val += array[friends[1]][1]
		friends[1] += 1
	friends[1] -= 1
	ans_set.append(ans_set[-1] + new_val - prev_val)
	ans = max(ans, ans_set[-1])
	if exit_code == 1:
		print(ans)
		exit()
print(ans)


(n, d) = input().split()
L = []
for i in range(int(n) + 1):
	if i == 0:
		L.append([0, 0])
	else:
		(m, f) = input().split()
		L.append([int(m), int(f)])
L.sort(key=lambda X: X[0])
Sum = 0
for i in range(1, int(n) + 1):
	Sum += L[i][1]
	L[i][1] = Sum
j = dif = 0
answer = 0
for i in range(1, int(n) + 1):
	if L[i][0] - L[j][0] < int(d):
		dif = L[i][0] - L[j][0]
	else:
		dif = L[i][0] - L[j][0]
		while dif >= int(d):
			j += 1
			dif = L[i][0] - L[j][0]
	if j == 0:
		answer = max(answer, L[i][1] - L[j][1])
	else:
		answer = max(answer, L[i][1] - L[j - 1][1])
print(answer)


import operator
(n, d) = list(map(int, input().split()))
l = []
for i in range(n):
	l.append(list(map(int, input().split())))
l = sorted(l, key=lambda x: x[0])
b = len(l)
friendship = 0
a = 0
(index, place) = (0, 0)
while index < b:
	while place < b and abs(l[index][0] - l[place][0]) < d:
		a += l[place][1]
		place += 1
	friendship = max(a, friendship)
	a -= l[index][1]
	index += 1
print(friendship)


(n, m) = [int(i) for i in input().split(' ')]
cost = []
f_factor = []
for i in range(n):
	s = input().split(' ')
	cost.append(int(s[0]))
	f_factor.append(int(s[1]))
sorted_map = sorted(zip(cost, f_factor))
cost = [x for (x, y) in sorted_map]
f_factor = [y for (x, y) in sorted_map]
maxans = 0
cumSum = [f_factor[0]]
for i in range(1, n):
	cumSum.append(cumSum[-1] + f_factor[i])
for i in range(n):
	low = i + 1
	high = n - 1
	findex = i
	while low <= high:
		mid = int((low + high) / 2)
		diff = cost[mid] - cost[i]
		if diff >= m:
			if cost[mid - 1] - cost[i] < m:
				findex = mid - 1
				break
			else:
				high = mid - 1
		else:
			findex = mid
			low = mid + 1
	temp = cumSum[findex] - cumSum[i] + f_factor[i]
	if maxans < temp:
		maxans = temp
print(maxans)


def main():
	(n, d) = [int(x) for x in input().split()]
	preffac = [0]
	friends = []
	for i in range(n):
		(m, s) = [int(x) for x in input().split()]
		friends.append((m, s))
	friends.sort()
	kon = -1
	wyn = 0
	ob = 0
	for pocz in range(n):
		if kon < pocz:
			kon = pocz
			ob = friends[pocz][1]
		while kon + 1 < n and friends[kon + 1][0] - friends[pocz][0] < d:
			ob += friends[kon + 1][1]
			kon += 1
		wyn = max(wyn, ob)
		ob -= friends[pocz][1]
	print(wyn)
main()


(n, d) = map(int, input().split())
friends = []
for i in range(n):
	(m, s) = map(int, input().split())
	friends.append([m, s])
max_f = 0
friends.sort(key=lambda x: x[0])
i = 0
j = 0
f = 0
while i < n:
	while j < n:
		diff = friends[j][0] - friends[i][0]
		if diff < d:
			f += friends[j][1]
			if f > max_f:
				max_f = f
			j += 1
		else:
			break
	f -= friends[i][1]
	i += 1
print(max_f)


from collections import OrderedDict
(n, d) = map(int, input().split())
a = dict()
for _ in range(n):
	(m, s) = map(int, input().split())
	if m in a:
		a[m] += s
	else:
		a[m] = s
a = OrderedDict(sorted(a.items()))
a = [item for item in a.items()]
k = 0
su = 0
mu = 0
for i in range(len(a)):
	su += a[i][1]
	while a[i][0] - a[k][0] >= d:
		su -= a[k][1]
		k += 1
	mu = max(mu, su)
print(mu)