#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)

def main():
    n,t=map(int,input().split(" "))
    a=list(map(int,input().split(" ")))
    ssum=[]
    ss=0
    for x in range(n-1,-1,-1):
        ss+=a[x]
        ssum.insert(0,ss)
    ssum.append(0)
    low=0
    high=n
    while low<=high:
        if ssum[low]-ssum[high]<=t:
            print(high-low)
            return
        else:
            if ssum[low+1]-ssum[high]<ssum[low]-ssum[high-1]:
                low+=1
            else:
                high-=1
    print(high-low)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)

def main():
    n,t=map(int,input().split(" "))
    a=list(map(int,input().split(" ")))
    ssum=[0 for x in range(n+1)]
    ss=0
    for x in range(n-1,-1,-1):
        ss+=a[x]
        ssum[x]=ss
    low=0
    high=n
    while low<=high:
        if ssum[low]-ssum[high]<=t:
            print(high-low)
            return
        else:
            if ssum[low+1]-ssum[high]<ssum[low]-ssum[high-1]:
                low+=1
            else:
                high-=1
    print(high-low)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)

def main():
    n,t=map(int,input().split(" "))
    a=list(map(int,input().split(" ")))
    low=0
    high=0
    sm=0
    ans=0
    while high<n:
        sm=sm+a[high]
        high+=1
        if sm>t:
            sm-=a[low]
            low+=1
        ans=max(ans,high-low)
    print(ans)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)

def main():
    n,t=map(int,input().split(" "))
    a=list(map(int,input().split(" ")))
    ssum=[0 for x in range(n+1)]
    ss=0
    for x in range(n-1,-1,-1):
        ss+=a[x]
        ssum[x]=ss
    low=0
    high=n
    while low<high:
        if ssum[low]-ssum[high]<=t:
            print(high-low)
            return
        else:
            if ssum[low+1]-ssum[high]<ssum[low]-ssum[high-1]:
                low+=1
            else:
                high-=1
    print(high-low)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)

def main():
    n,t=map(int,input().split(" "))
    a=list(map(int,input().split(" ")))
    ssum=[]
    ss=0
    for x in range(n-1,-1,-1):
        ss+=a[x]
        ssum.insert(0,ss)
    ssum.append(0)
    low=0
    high=n
    while low<high:
        if ssum[low]-ssum[high]<=t:
            print(high-low)
            return
        else:
            if ssum[low+1]-ssum[high]<ssum[low]-ssum[high-1]:
                low+=1
            else:
                high-=1
    print(high-low)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    main()


#!/usr/bin/env python
import os
import sys
from io import BytesIO, IOBase
#from bisect import bisect_left as bl                #c++ lowerbound bl(array,element)
#from bisect import bisect_right as br               #c++ upperbound br(array,element)

def main():
    n,t=map(int,input().split(" "))
    a=list(map(int,input().split(" ")))
    ssum=[]
    ss=0
    for x in range(n-1,-1,-1):
        ss+=a[x]
        ssum.insert(0,ss)
    ssum.append(0)
    low=0
    high=n
    while low<=high:
        if ssum[low]-ssum[high]<=t:
            print(high-low)
            return
        else:
            low+=1
    print(high-low)

#-----------------------------BOSS-------------------------------------!
# region fastio

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

# endregion

if __name__ == "__main__":
    main()


n, t = map(int, input().strip().split())
arr = list(map(int, input().strip().split()))

s, counter = 0, 0
for i in range(n):
	s += arr[i]
	if s > t:
		s -= arr[counter]
		counter += 1
print(n-counter)


from math import ceil
def isPossible(arr, l, t):
	currSum = sum(arr[:l])
	if currSum <= t:
		return True
	for i in range(l, len(arr)):
		currSum -= arr[i-l]
		currSum += arr[i]
		if currSum <= t:
			return True
	return False

n, t = map(int, input().strip().split())
arr = list(map(int, input().strip().split()))

low = 0
high = n
curr = (low+high)//2
while low < high:
	if isPossible(arr, curr, t):
		if low == curr:
			break
		low = curr
	else:
		high = curr
	curr = (low+high)//2
print(curr)


from math import ceil
def isPossible(arr, l, t):
	currSum = sum(arr[:l])
	if currSum <= t:
		return True
	for i in range(l, len(arr)):
		currSum -= arr[i-l]
		currSum += arr[i]
		if currSum <= t:
			return True
	return False

n, t = map(int, input().strip().split())
arr = list(map(int, input().strip().split()))

low = 0
high = n
curr = n
while low < high:
	if isPossible(arr, curr, t):
		if low == curr:
			break
		low = curr
	else:
		high = curr
	curr = (low+high)//2
print(curr)


#------------------------------what is this I don't know....just makes my mess faster--------------------------------------
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")

#----------------------------------Real game starts here--------------------------------------
'''

___________________THIS IS AESTROIX CODE________________________
                       KARMANYA GUPTA

'''
#_______________________________________________________________#
def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x-1)
def lower_bound(li, num): #return 0 if all are greater or equal to
	answer = -1
	start = 0
	end = len(li)-1

	while(start <= end):
		middle = (end+start)//2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer #index where x is not less than num
def upper_bound(li, num): #return n-1 if all are small or equal
	answer = -1
	start = 0
	end = len(li)-1

	while(start <= end):
		middle = (end+start)//2

		if li[middle] <= num:
			answer = middle
			start = middle + 1

		else:
			end = middle - 1
	return answer #index where x is not greater than num

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

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1]*(n+1)
	arr[0],arr[1], i = 0, 0, 2
	while(i*i <= n):
		if arr[i] == 1:
			j = i+i
			while(j <= n):
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans
def nc2(x):
	if x == 1:
		return 0
	else:
		return x*(x-1)//2
#_______________________________________________________________#

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


#------------------------------what is this I don't know....just makes my mess faster--------------------------------------
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")

#----------------------------------Real game starts here--------------------------------------
'''

___________________THIS IS AESTROIX CODE________________________
                       KARMANYA GUPTA

'''
#_______________________________________________________________#
def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x-1)
def lower_bound(li, num): #return 0 if all are greater or equal to
	answer = -1
	start = 0
	end = len(li)-1

	while(start <= end):
		middle = (end+start)//2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer #index where x is not less than num
def upper_bound(li, num): #return n-1 if all are small or equal
	answer = -1
	start = 0
	end = len(li)-1

	while(start <= end):
		middle = (end+start)//2

		if li[middle] <= num:
			answer = middle
			start = middle + 1

		else:
			end = middle - 1
	return answer #index where x is not greater than num

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

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1]*(n+1)
	arr[0],arr[1], i = 0, 0, 2
	while(i*i <= n):
		if arr[i] == 1:
			j = i+i
			while(j <= n):
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans
def nc2(x):
	if x == 1:
		return 0
	else:
		return x*(x-1)//2
#_______________________________________________________________#

for _ in range(1):
	n, t = map(int, input().split())
	book = list(map(int, input().split()))
	book.insert(0,0)
	ans = 0
	for i in range(1,n+1):
		book[i] += book[i-1]
	l, r = 1,1
	#print(book)
	while(True):
		#print(t, book[r] - book[l-1], ans, r, l)
		if r <= n and l<=r:
			if book[r] - book[l-1] <= t:
				ans = max(ans, r-l+1)
				r += 1
			else:
				l += 1
		else:
			break
	print(ans)


#------------------------------what is this I don't know....just makes my mess faster--------------------------------------
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")

#----------------------------------Real game starts here--------------------------------------
'''

___________________THIS IS AESTROIX CODE________________________
                       KARMANYA GUPTA

'''
#_______________________________________________________________#
def fact(x):
	if x == 0:
		return 1
	else:
		return x * fact(x-1)
def lower_bound(li, num): #return 0 if all are greater or equal to
	answer = -1
	start = 0
	end = len(li)-1

	while(start <= end):
		middle = (end+start)//2
		if li[middle] >= num:
			answer = middle
			end = middle - 1
		else:
			start = middle + 1
	return answer #index where x is not less than num
def upper_bound(li, num): #return n-1 if all are small or equal
	answer = -1
	start = 0
	end = len(li)-1

	while(start <= end):
		middle = (end+start)//2

		if li[middle] <= num:
			answer = middle
			start = middle + 1

		else:
			end = middle - 1
	return answer #index where x is not greater than num

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

def sieve_of_eratosthenes(n):
	ans = []
	arr = [1]*(n+1)
	arr[0],arr[1], i = 0, 0, 2
	while(i*i <= n):
		if arr[i] == 1:
			j = i+i
			while(j <= n):
				arr[j] = 0
				j += i
		i += 1
	for k in range(n):
		if arr[k] == 1:
			ans.append(k)
	return ans
def nc2(x):
	if x == 1:
		return 0
	else:
		return x*(x-1)//2
#_______________________________________________________________#

for _ in range(1):
	n, t = map(int, input().split())
	book = list(map(int, input().split()))
	book.insert(0,0)
	ans = 0
	for i in range(1,n+1):
		book[i] += book[i-1]
	l, r = 1,1
	#print(book)
	while(True):
		#print(t, book[r] - book[l-1], ans, r, l)
		r = max(r, l)
		if r <= n and l<=r:
			if book[r] - book[l-1] <= t:
				ans = max(ans, r-l+1)
				r += 1
			else:
				l += 1
		else:
			break
	print(ans)


n,t=map(int,input().split())
list1=list(map(int,input().split()))
for i in range(1,n):
    list1[i]+=list1[i-1]
m=0
s=0
for i in range(n):
    s+=list1[i]
    for j in range(n-1,-1,-1):
        if(list1[j]-s<=t):
            if(m<(j-i)):
                m=j-i
mm=0
if(sum(list1)<=t):
    mm=n
print(max(m,mm))


n,t=map(int,input().split())
list1=list(map(int,input().split()))
for i in range(1,n):
    list1[i]+=list1[i-1]
list1=[0]+list1
x=list1[-1]
c=0
for i in range(n+1):
    if(x-list1[i]<=t):
        break
    else:
        c+=1

print(n-c)


n,t=map(int,input().split())
list1=list(map(int,input().split()))
s=0
c=0
j=0
cc=0
for i in range(n):
    s+=list1[i]
    c+=1
    if(s>t):
        s-=list1[j]
        c-=1
        j+=1
    if(c>cc):
        cc=c

print(cc)


n,t=map(int,input().split())
list1=list(map(int,input().split()))
s=0
c=0
j=0
cc=0
for i in range(n):
    s+=list1[i]
    c+=1
    if(s>t):
        s-=list1[j]
        c-=1
    j+=1
    if(c>cc):
        cc=c
print(cc)


n,t=map(int,input().split())
list1=list(map(int,input().split()))
for i in range(1,n):
    list1[i]+=list1[i-1]
list1=[0]+list1
m=0
s=0
for i in range(n+1):
    s+=list1[i]
    for j in range(n,-1,-1):
        if(list1[j]-s<=t):
            if(m<(j-i)):
                m=j-i
mm=0
if(sum(list1)<=t):
    mm=n
print(max(m,mm))


n,t= map(int, input().split())
count=0
l= list(map(int, input().split()))
p,k,s=0,0,0

for i in range(n):
    s+=l[i]
    if s>t:
        s-=l[k]
        k+=1

print(n-k)


n,t= map(int, input().split())
count=0
l= list(map(int, input().split()))
l.sort()
i=0
flag=0

if sum(l)<=t:
    print(n)
    quit()
while t>0:

    t= t-l[i]
    i+=1
    count+=1
    if t<0:
        print(count-1)
        flag=1
if flag==0:
    print(count)


n,t= map(int, input().split())
count=0
l= list(map(int, input().split()))
l.sort()
i=0
flag=0
while t>0:

    t= t-l[i]
    i+=1
    count+=1
    if t<0:
        print(count-1)
        flag=1
if flag==0:
    print(count)


n, t = map(int, input().split())
sum = 0
a = list(map(int, input().split()[:n]))
a = sorted(a)

for i in range(n):
    sum = sum + a[i]
    if sum == t or sum > t:
        a = i
        print(a)
        break

    elif sum < t and i==n-1:
        print(i+1)


n, t = map(int, input().split())
sum = 0
a = list(map(int, input().split()[:n]))
a = sorted(a)
for i in range(n):
    sum = sum + a[i]
    if sum == t or sum>t:
        print(i)
        break

    else:
        print(i+1)


n, t = map(int, input().split())
sum = 0
a = list(map(int, input().split()[:n]))

for i in range(n):
    sum = sum + a[i]
    if  sum > t:
        a = i
        print(a)
        break
    elif sum==t:
        print(i+1)

    elif sum < t and i==n-1:
        print(i+1)


n, t = map(int, input().split())
ls = list(map(int, input().split()))
s = j = 0
for i in range(n):
    s += ls[i]
    if s > t:
        s -= ls[j]
        j += 1
print(n-j)


n, t = map(int, input().split())
sum = 0
a = list(map(int, input().split()[:n]))
a = sorted(a)

for i in range(n):
    sum = sum + a[i]
    if  sum > t:
        a = i
        print(a)
        break
    elif sum==t:
        print(i+1)

    elif sum < t and i==n-1:
        print(i+1)


n, t = map(int, input().split())
sum = 0
a = list(map(int, input().split()[:n]))
a = sorted(a)
for i in range(n):
    sum = sum + a[i]
    if sum == t or sum>t:
        print(i)
        break


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

def iinput():
    return int(input())

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

def rinput():
    return map(int, tinput())

def rlinput():
    return list(rinput())

n,t = rinput()
A = rlinput()
max = 0
for i in range(n):
    total = 0
    count = 0
    for j in range(i,n):
        if t-total < A[j]:
            break
        total += A[j]
        count += 1
    if count > max:
        max = count
print(max)


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

def iinput():
    return int(input())

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

def rinput():
    return map(int, tinput())

def rlinput():
    return list(rinput())

n,t = rinput()
A = rlinput()
max = 0
for i in range(n):
    if i == 0:
        total = 0
        count = 0
        for j in range(i,n):
            if t-total < A[j]:
                break
            total += A[j]
            count += 1

    else:
        total = total - A[i-1]
        count -= 1
        for j in range(end,n):
            if t-total < A[j]:
                break
            total += A[j]
            count += 1
    if count > max:
        max = count
    end = j
    if end == n-1:
        print(max)
        break
else:
    print(max)


n,t = map(int,input().split())
a = [int(i) for i in input().split()]
j = -1
s = 0
ans = 0
for i in range(n):
	if s+a[i]<=t:
		s+=a[i]
	else:
		s+=a[i]
		while s>t:
			j+=1
			s-=a[j]
	ans=(max(ans,i-j))
print(ans)


n,t = map(int,input().split())
a = [int(i) for i in input().split()]
a.sort()
s = 0
k = 0
for i in range(n):
	if s+a[i]>=t:
		break
	else:
		s+=a[i]
		k+=1
print(k)


n,t = map(int,input().split())
a = [int(i) for i in input().split()]
a.sort()
s = 0
k = 0
for i in range(n):
	if s+a[i]>=t:
		print(k)
		break
	else:
		s+=a[i]
		k+=1


n,t = map(int,input().split())
a = [int(i) for i in input().split()]
max_ = 0
for i in range(n):
	s = 0
	k = 0
	for j in range(i,n):
		if s+a[j]>t:
			break
		else:
			s+=a[j]
			k+=1
	if k>max_:
		max_=k
print(max_)


n,t = map(int,input().split())
a = [int(i) for i in input().split()]
a.sort()
s = 0
k = 0
for i in range(n):
	if s+a[i]>t:
		break
	else:
		s+=a[i]
		k+=1
print(k)


import sys

def input():    return sys.stdin.readline().strip()
def iinput():   return int(input())
def rinput():   return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7

n, t = rinput()
a = get_list()

s, j = 0, 0
ans = 0
for i in range(n):
	s += a[i]
	if s>t:
		s -= a[j]
		j += 1

print(n-j)


import sys

def input():    return sys.stdin.readline().strip()
def iinput():   return int(input())
def rinput():   return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7

n, t = rinput()
a = get_list()
ans = 0
for i in range(n):
	if a[i]<=t:
		s = a[i]
		j = i+1
		while(j<n and s+a[j]<=t):
			s+=a[j]
			j+=1
		ans = max(ans, j-i)

print(ans)


import sys

def input():    return sys.stdin.readline().strip()
def iinput():   return int(input())
def rinput():   return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7

n, t = rinput()
a = get_list()

p = q = sum(a)

if p<=t:
	print(n)
else:
	flag = 0
	for i in range(1, n, 1):
		p-=a[i-1]
		q-=a[-i]

		if p<=t or q<=t:
			print(n-i)
			flag = 1
			break
	if flag == 0:
		print(0)


import sys

def input():    return sys.stdin.readline().strip()
def iinput():   return int(input())
def rinput():   return map(int, sys.stdin.readline().strip().split())
def get_list(): return list(map(int, sys.stdin.readline().strip().split()))
mod = int(1e9)+7

n, t = rinput()
a = get_list()

p = q = sum(a)

for i in range(1, n, 1):
	p-=a[i-1]
	q-=a[-i]

	if p<=t or q<=t:
		print(n-i)
		break


n, t = map(int,input().split())
arrMinutes = list(map(int,input().split()))
amount = []
count = 0
sumMinute = 0
index = 0
for i in range(n):
    if sumMinute + arrMinutes[i] <= t:
        sumMinute = sumMinute + arrMinutes[i]
        count += 1
        index = i
    else:
        break
if count == n:
    print(count)
else:
    left = 0
    amount.append(count)
    for i in range(index + 1,n):
        sumMinute = sumMinute + arrMinutes[i]
        for j in range(left,i + 1):
            if sumMinute > t:
                sumMinute = sumMinute - arrMinutes[left]
                left += 1
            else:
                break
        amount.append(i - left + 1)
    print(max(amount))


n, t = map(int,input().split())
arrMinutes = list(map(int,input().split()))
cnt = [0]*10001
for i in range(n):
    cnt[arrMinutes[i]] += 1
count = 0
sumMinute = 0
for i in range(len(cnt)):
    if cnt[i] != 0:
        for j in range(cnt[i]):
            if sumMinute + i <= t:
                sumMinute = sumMinute + i
                count += 1
            else:
                print(count)
                exit()
print(count)


n, t = map(int,input().split())
arrMinutes = list(map(int,input().split()))
amount = []
count = 0
sumMinute = 0
index = 0
for i in range(n):
    if sumMinute + arrMinutes[i] <= t:
        sumMinute = sumMinute + arrMinutes[i]
        count += 1
        index = i
    else:
        break
if count == n:
    print(count)
else:
    left = 0
    amount.append(count)
    for i in range(count,n):
        sumMinute = sumMinute + arrMinutes[i]
        for j in range(left,i + 1):
            if sumMinute > t:
                sumMinute = sumMinute - arrMinutes[left]
                left = left + 1
            else:
                break
        amount.append(i - left + 1)
    print(max(amount))


num,k = map(int,input().split())
listnum = list(map(int,input().split()))
count = 1
for i in range(1,num):
    linhcanh = 1
    for j in range(i):
        if listnum[i] == listnum[j]:
            linhcanh = 0
            break
    if linhcanh == 1:
        count += 1
    if count == k:
        right = i
        break
leftTrue = 0
if count != k:
    print("-1 -1")
else:
    for i in range(right +1):
        lc1 = 1
        for j in range(i + 1,right + 1):
            if listnum[leftTrue] == listnum[j]:
                lc1 = 0
                break
        if lc1 == 1:
            print(str(leftTrue + 1),str(right + 1))
            exit()
        else:
            leftTrue += 1


n, t = map(int,input().split())
arrMinutes = list(map(int,input().split()))
amount = []
for i in range(n):
    count = 0
    sumMinute = 0
    for j in range(i,n):
        if sumMinute + arrMinutes[j] <= t:
            sumMinute = sumMinute + arrMinutes[j]
            count += 1
        else:
            break
    amount.append(count)
print(max(amount))

# for i in range(n):
    # cnt[arrMinutes[i]] += 1
# count = 0
# sumMinute = 0
# for i in range(len(cnt)):
    # if cnt[i] != 0:
        # for j in range(cnt[i]):
            # if sumMinute + i <= t:
                # print(i,end =" ")
                # sumMinute = sumMinute + i
                # count += 1
            # else:
                # print(sumMinute)
                # print(count)
                # exit()
# print(count)


n, t = map(int,input().split())
arrMinutes = list(map(int,input().split()))
amount = []
count = 0
sumMinute = 0
index = 0
for i in range(n):
    if sumMinute + arrMinutes[i] <= t:
        sumMinute = sumMinute + arrMinutes[i]
        count += 1
        index = i
    else:
        break
if count == n:
    print(count)
else:
    left = 0
    amount.append(count)
    for i in range(index + 1,n):
        sumMinute = sumMinute + arrMinutes[i]
        for j in range(left,i + 1):
            if sumMinute >= t:
                sumMinute = sumMinute - arrMinutes[left]
                left += 1
            else:
                break
        amount.append(i - left + 1)
    print(max(amount))


n, t = map(int,input().split())
arrMinutes = list(map(int,input().split()))
cnt = [0]*100001
for i in range(n):
    cnt[arrMinutes[i]] += 1
count = 0
sumMinute = 0
for i in range(len(cnt)):
    if cnt[i] != 0:
        for j in range(cnt[i]):
            if sumMinute + i <= t:
                sumMinute = sumMinute + i
                count += 1
            else:
                print(count)
                exit()
print(count)


    n, t = map(int,input().split())
    arrMinutes = list(map(int,input().split()))
    amount = []
    count = 0
    sumMinute = 0
    index = 0
    for i in range(n):
        if sumMinute + arrMinutes[i] <= t:
            sumMinute = sumMinute + arrMinutes[i]
            count += 1
            index = i
        else:
            break
    if count == n:
        print(count)
    else:
        left = 0
        amount.append(count)
        for i in range(count,n):
            sumMinute = sumMinute + arrMinutes[i]
            for j in range(left,i + 1):
                if sumMinute > t:
                    sumMinute = sumMinute - arrMinutes[left]
                    left = left + 1
                else:
                    break
            amount.append(i - left + 1)
        print(max(amount))


n, t = map(int,input().split())
arrMinutes = list(map(int,input().split()))
amount = []
count = 0
sumMinute = 0
index = 0
for i in range(n):
    if sumMinute + arrMinutes[i] <= t:
        sumMinute = sumMinute + arrMinutes[i]
        count += 1
        index = i
    else:
        break
if count == n:
    print(count)
else:
    left = 0
    amount.append(count)
    for i in range(index + 1,n):
        sumMinute = sumMinute + arrMinutes[i]
        for j in range(left,i + 1):
            if sumMinute > t:
                sumMinute = sumMinute - arrMinutes[left]
                left = left + 1
            else:
                break
        amount.append(i - left + 1)
    print(max(amount))


import sys

n, t = map(int, input().split())
a = list(map(int, input().split()))
tottime = 0
left = 0
cnt = 0
finalcnt = 0
for x in a:
    tottime += x
    cnt += 1
    while tottime > t:
        cnt -= 1
        tottime -= a[left]
        left += 1
    finalcnt = max(finalcnt, cnt)
print(finalcnt)


import array as arr

n = int(input())
t = int(input())
a = arr.array('i', [])
for i in range(n):
    x = int(input())
    a.append(x)
tottime = 0
left = 0
cnt = 0
finalcnt = 0
for x in a:
    tottime += x
    cnt += 1
    while tottime > t:
        cnt -= 1
        tottime -= a[left]
        left += 1
    finalcnt = max(finalcnt, cnt)
print(finalcnt)


mod = 1000000007
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,t=f()
l=sorted(il())
sf = [0]*n
sf[0] = l[0]
for i in range(1, n):
    sf[i]=sf[i-1]+l[i]
c=0
for i in range(n):
    if sf[i]<=t:
        c+=1
print(c)


mod = 1000000007
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,t=f()
l=il()
i=0
j=0
sm=0
mx=0
while i<n and j<n:
    if sm+l[j]<=t:
        sm+=l[j]
        j+=1
        mx=max(mx,j-i)
    else:
        sm-=l[i]
        i+=1
print(mx)


mod = 1000000007
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,t=f()
l=il()
sf = [0]*n
sf[0] = l[0]
for i in range(1, n):
    sf[i]=sf[i-1]+l[i]
c=0
for i in range(n):
    if sf[i]<=t:
        c+=1
print(c)


n_livros, tempo_livre = map(int, input().split())
minutos_livro = list(map(int, input().split()))
i, j, cont, livros_lidos = 0, 0, 0, 0

while i < n_livros:
	cont +=  minutos_livro[i]
	if cont > tempo_livre:
		cont -= minutos_livro[j]
		j += 1
	livros_lidos = i - j + 1
	i += 1

print(livros_lidos)


n_livros, tempo_livre = map(int, input().split())

minutos_livro = list(map(int, input().split()))

livros = 0
min_gastos = 0

for i in range(n_livros):
	if tempo_livre >= min_gastos + minutos_livro[i]:
		livros += 1
		min_gastos += minutos_livro[i]

print(livros)


n_livros, tempo_livre = map(int, input().split())

minutos_livro = list(map(int, input().split()))

qtd = []

for i in range(n_livros):
	min_gastos = 0
	posicao = i
	livros = 0
	while posicao < n_livros:
		if tempo_livre >= min_gastos + minutos_livro[posicao]:
			livros += 1
			min_gastos += minutos_livro[posicao]
		else:
			break
		posicao += 1
	qtd.append(livros)

print(max(qtd))


def check(x,A):
    n = len(A)
    sum = 0
    for i in range(x):
        sum+=A[i]
    if(sum<=t):
        return True
    for i in range(x,n):
        sum-=A[i-x];sum+=A[i]
        if(sum<=t):
            return True
    return False

n,t = map(int,input().split())
A = list(map(int,input().split()))
l=0;h=n
ans = 0
while(l<h):
    mid = (l+h+1)//2
    if(check(mid,A)):
        l = mid
        ans = mid
    else:
        h = mid-1
print(ans)


n,t = map(int,input().split())
A = list(map(int,input().split()))
if(n==1):
    if(A[0]<=t):
        print(1)
    else:
        print(0)
else:
    i = 0;j=1
    sum = A[i]
    ans = 0
    while(i<n-1 and j<n):
        sum+=A[j]
        if(sum<=t):
            j+=1
        else:
            ans = max(j-i,ans)
            sum = A[i+1]
            i+=1;j=i+1
    ans = max(ans,j-i)
    print(ans)


n,t = map(int,input().split())
A = list(map(int,input().split()))
i = 0;j=1
sum = A[i]
ans = 0
while(i<n-1 and j<n):
    sum+=A[j]
    if(sum<=t):
        j+=1
    else:
        ans = max(j-i,ans)
        sum = A[i+1]
        i+=1;j=i+1
ans = max(ans,j-i)
print(ans)


n,t=map(int,input().split())
a=list(map(int,input().split()))
count=0
sum=0
s=0
max1=0
i=0
while i<n:
    if sum+a[i]>t:
        if sum!=0:
            sum-=a[s]
            s+=1
            if count>max1:
                max1=count
            count-=1
            i-=1
    else:
        sum+=a[i]
        count+=1
    i+=1
print(count)


n,t=map(int,input().split())
a=list(map(int,input().split()))
count=0
sum=0
s=0
max1=0
i=0
while i<n:
    if sum+a[i]>t:
        if sum!=0:
            sum-=a[s]
            s+=1
        if count>max1:
            max1=count
        count-=1
        i-=1
    else:
        sum+=a[i]
        count+=1
    i+=1
print(count)


n,t=map(int,input().split())
a=list(map(int,input().split()))
count=0
sum=0
s=0
max1=0
i=0
while i<n:
    if sum+a[i]>t:
        if sum!=0:
            sum-=a[s]
            s+=1
            if count>max1:
                max1=count
            count-=1
            i-=1
    else:
        sum+=a[i]
        count+=1
    i+=1
print(max1)


n,t=map(int,input().split())
a=list(map(int,input().split()))
count=0
sum=0
s=0
max1=0
i=0
while i<n:
    if sum+a[i]>t:
        if sum!=0:
            sum-=a[s]
            s+=1
            if count>max1:
                max1=count
            count-=1
            i-=1
    else:
        sum+=a[i]
        count+=1
    i+=1
if count>max1:
    max1=count
print(max1)


n, t = map(int, input().split())
a = [0] + [int(i) for i in input().split()]
cs = 0
pref_sums = []

for i in a:
    cs += i
    pref_sums.append(cs)

ans = 0
for i in range(1, n+1):
    l = i - 1
    r = n + 1
    while r - l > 1:
        m = l + (r - l) // 2
        diff = pref_sums[m] - pref_sums[i - 1]
        if diff <= t:
            l = m
        else:
            r = m
    ans = max(ans, l - i + 1)

print(ans)


n, t = map(int, input().split())
a = [0] + [int(i) for i in input().split()]
cs = 0
pref_sums = []

for i in a:
    cs += i
    pref_sums.append(cs)

ans = 0
for i in range(1, n):
    l = i - 1
    r = n + 1
    while r - l > 1:
        m = l + (r - l) // 2
        diff = pref_sums[m] - pref_sums[i - 1]
        if diff <= t:
            l = m
        else:
            r = m
    ans = max(ans, l - i + 1)

print(ans)


'''Задача разложить число на простые множители'''
'''
N = int(input())
sum = N
for j in range(2,N+1):
    while N % j == 0:
        N //= j
        sum += N
print(sum)
'''
# Задача найти максимальное число книг

n,t = map(int,input().split())
A = list(map(int,input().split()))

'''k = 0
for i in range(len(A)):
    if A[i] < t:
        k = i
        break
c = 0
for j in range(k, len(A)):
    S = 0
    if A[j] > t:
        continue
    m = j
    lenght = 0
    while S <= t and m < len(A):
        S += A[m]
        m += 1
        lenght = m-j
    if m == len(A) and lenght > c and S <= t:
        c = lenght
    elif lenght-1 > c :
        c = lenght-1
print(c)
'''
l = 0
r = 0

lenght = 0
c = 0
S = 0
while r < len(A):
    if A[r] > t:
        r += 1
        l += 1
        continue
    while S <= t and r < len(A):
        S += A[r]
        r += 1
    if r == len(A) and S <= t:
        r += 1
    S = S - A[l]
    lenght = r-1-l
    if lenght > c:
        c = lenght
    l += 1

print(c)


'''Задача разложить число на простые множители'''
'''
N = int(input())
sum = N
for j in range(2,N+1):
    while N % j == 0:
        N //= j
        sum += N
print(sum)
'''
# Задача найти максимальное число книг

n,t = map(int,input().split())
A = list(map(int,input().split()))

k = 0
for i in range(len(A)):
    if A[i] < t:
        k = i
c = 0
for j in range(k, len(A)):
    S = 0
    if A[j] > t:
        continue
    m = j
    lenght = 0
    while S <= t and m < len(A):
        S += A[m]
        m += 1
        lenght = m-j
    if m == len(A) and lenght > c and S <= t:
        c = lenght
    elif lenght-1 > c :
        c = lenght-1
print(c)


'''Задача разложить число на простые множители'''
'''
N = int(input())
sum = N
for j in range(2,N+1):
    while N % j == 0:
        N //= j
        sum += N
print(sum)
'''
# Задача найти максимальное число книг

n,t = map(int,input().split())
A = list(map(int,input().split()))
i = 0
while A[i] > t:
    i += 1   # первый кандидат, до него не интересны
c = 0
for j in range(i, len(A)):
    S = 0
    if A[j] > t:
        continue
    m = j
    lenght = 0
    while S <= t and m < len(A):
        S += A[m]
        m += 1
        lenght = m-j
    if m == len(A) and lenght > c and S <= t:
        c = lenght
    elif lenght-1 > c :
        c = lenght-1
print(c)


'''Задача разложить число на простые множители'''
'''
N = int(input())
sum = N
for j in range(2,N+1):
    while N % j == 0:
        N //= j
        sum += N
print(sum)
'''
# Задача найти максимальное число книг

n,t = map(int,input().split())
A = list(map(int,input().split()))

k = 0
for i in range(len(A)):
    if A[i] < t:
        k = i
        break
c = 0
for j in range(k, len(A)):
    S = 0
    if A[j] > t:
        continue
    m = j
    lenght = 0
    while S <= t and m < len(A):
        S += A[m]
        m += 1
        lenght = m-j
    if m == len(A) and lenght > c and S <= t:
        c = lenght
    elif lenght-1 > c :
        c = lenght-1
print(c)


n,t=map(int, input().split())
kek=tuple(map(int, input().split()))
l=0
s=0
res=0
for r in range(n):
    s+=kek[r]
    while s>t:
        s-=kek[l]
        l+=1
    res=max(res,r-l+1)
print(res)


n,t=map(int, input().split())
kek=tuple(map(int, input().split()))
itog=0
for i in range(n):
    summa=0
    kol=0
    while summa<=t:
        if summa+kek[i]<=t:
            summa+=kek[i]
            kol+=1
            if i<n-1:
                i+=1
            else:
                itog = max(itog, kol)
                break
        else:
            itog = max(itog, kol)
            break
print(itog)


n,t=map(int, input().split())
kek=[]
kek+=map(int, input().split())
itog=0
for i in range(n):
    summa=0
    kol=0
    while summa<t:
        if summa+kek[i]<t:
            summa+=kek[i]
            kol+=1
            if i<n-1:
                i+=1
            else:
                itog = max(itog, kol)
                break
        else:
            itog = max(itog, kol)
            break
print(itog)


n,t=map(int, input().split())
kek=[]
kek+=map(int, input().split())
itog=0
for i in range(n):
    summa=0
    kol=0
    while summa<=t:
        if summa+kek[i]<=t:
            summa+=kek[i]
            kol+=1
            if i<n-1:
                i+=1
            else:
                itog = max(itog, kol)
                break
        else:
            itog = max(itog, kol)
            break
print(itog)


n,t=map(int, input().split())
kek=tuple(map(int, input().split()))
print(kek)
itog=0
for i in range(n):
    summa=0
    kol=0
    while summa<=t:
        if summa+kek[i]<=t:
            summa+=kek[i]
            kol+=1
            if i<n-1:
                i+=1
            else:
                itog = max(itog, kol)
                break
        else:
            itog = max(itog, kol)
            break
print(itog)


n, t = map(int, input().split())
a = list(map(int, input().split()))

i = j = 0
ans = 0
temp = 0
while j < n:
    # print(i, j)
    if t >= a[j]:
        temp += 1
        t -= a[j]
        j += 1
    else:
        if i + 1 < n:
            t += a[i]
            i += 1
            ans = max(temp, ans)
            temp = max(0, temp - 1)
            j = max(j, i)
        else:
            break
ans = max(ans, temp)
print(ans)


n, t = map(int, input().split())
a = list(map(int, input().split()))

i = j = 0
ans = 0
temp = 0
while j < n:
    # print(i, j, t)
    # print(temp)
    if t >= a[j]:
        temp += 1
        t -= a[j]
        j += 1
    else:
        if i + 1 < n:
            t += (a[i] if i < j else 0)
            i += 1
            ans = max(temp, ans)
            temp = (temp - 1) if i <= j else 0
            j = max(j, i)
        else:
            break
ans = max(ans, temp)
print(ans)


def zip_sorted(a,b):

	# sorted  by a
	a,b = zip(*sorted(zip(a,b)))
	# sorted by b
	sorted(zip(a, b), key=lambda x: x[1])

	return a,b

n,t = [int(n1) for n1 in input().split()]
a   = [int(n1) for n1 in input().split()]
b = [0]*n

j = 0
spent = 0
t1 = t
for i in range(len(b)):
	while t1>0 and j<n:
		if t1>=a[j]:
			b[i] = b[i]+1
			t1= t1-a[j]
			j = j+1
		else:
			break
	if a[i]<t:
		t1 = t1 + a[i]
	else:
		t1 = t
		j = i+1
	if i!=n-1:
		if b[i]>0:
			b[i+1] = b[i] - 1

print(max(b))

'''
for i in range(n):
for j in range(n):
for k1 in range(len(a)):
for k2 in range(len(a)):
for k3 in range(len(a)):

'''


def zip_sorted(a,b):

	# sorted  by a
	a,b = zip(*sorted(zip(a,b)))
	# sorted by b
	sorted(zip(a, b), key=lambda x: x[1])

	return a,b

n,t = [int(n1) for n1 in input().split()]
a   = [int(n1) for n1 in input().split()]
b = [0]*n

j = 0
spent = 0
t1 = t
for i in range(len(b)):
	while t1>0 and j<n:
		if t1>=a[j]:
			b[i] = b[i]+1
			j = j+1
			t1= t1-a[i]
		else:
			break
	t1 = t1 + a[i]
	if i!=n-1:
		if b[i]>0:
			b[i+1] = b[i] - 1

print(max(b))

'''
for i in range(n):
for j in range(n):
for k1 in range(len(a)):
for k2 in range(len(a)):
for k3 in range(len(a)):

'''


def zip_sorted(a,b):

	# sorted  by a
	a,b = zip(*sorted(zip(a,b)))
	# sorted by b
	sorted(zip(a, b), key=lambda x: x[1])

	return a,b

n,t = [int(n1) for n1 in input().split()]
a   = [int(n1) for n1 in input().split()]
b = [0]*n

j = 0
spent = 0
t1 = t
for i in range(len(b)):
	while t1>0 and j<n:
		if t1>=a[j]:
			b[i] = b[i]+1
			t1= t1-a[j]
			j = j+1
		else:
			break
	t1 = t1 + a[i]
	if i!=n-1:
		if b[i]>0:
			b[i+1] = b[i] - 1

print(max(b))

'''
for i in range(n):
for j in range(n):
for k1 in range(len(a)):
for k2 in range(len(a)):
for k3 in range(len(a)):

'''


n,t=map(int,input().split())
l=list(map(int,input().split()))
i=0
ans=0
l.sort()

while i<=n-1:
    if t>=l[i]:
        ans+=1
        t-=l[i]
        i+=1
    else:
        break
print(ans)


n,t=map(int,input().split())
l=list(map(int,input().split()))
i=0
ans=0
l.sort()
while i<=n-1:
    if t>=l[i]:
        ans+=1
        t-=l[i]
        i+=1
print(ans)


def atMostSum(arr, n, k):
	_sum = 0
	cnt = 0
	maxcnt = 0
	for i in range(n):
		if ((_sum + arr[i]) <= k):
			_sum += arr[i]
			cnt += 1
		elif(_sum != 0):
			_sum = _sum - arr[i - cnt] + arr[i]
		maxcnt = max(cnt, maxcnt)
	return maxcnt
n,k=map(int,input().split())
arr=list(map(int,input().split()))
print(atMostSum(arr, n, k))


n,t=map(int,input().split())
l=list(map(int,input().split()))
i=0
ans=0
l.sort()
while t>=l[i] and i<=n-1:
    ans+=1
    t-=l[i]
    i+=1
print(ans)


from math import *
from collections import *
n,m = map(int,input().split())
a = list(map(int,input().split()))
pre = [0,a[0]]
for i in range(1,n):
    pre.append(pre[-1]+a[i])
i = 0
j = 1
maxx = 0
while(i < n):
    while(j < n and pre[j] - pre[i] <= m):
        j += 1
    maxx = max(maxx,j-i-1)
    i += 1
print(maxx)


from math import *
from collections import *
n,m = map(int,input().split())
a = list(map(int,input().split()))
pre = [0,a[0]]
for i in range(1,n):
    pre.append(pre[-1]+a[i])
i = 0
j = n-1
while(j >= i):
    if(pre[j+1] - pre[i] > m):
        if(a[i] > a[j]):
            i += 1
        else:
            j -= 1
    else:
        print(j-i+1)
        break
else:
    print(0)


from math import *
from collections import *
n,m = map(int,input().split())
a = list(map(int,input().split()))
pre = [0,a[0]]
for i in range(1,n):
    pre.append(pre[-1]+a[i])
i = 0
j = 1
maxx = 0
while(i < n):
    #print(i,j)
    while(j <= n and pre[j] - pre[i] <= m):
        j += 1
    maxx = max(maxx,j-i-1)
    i += 1
print(maxx)


n,m=map(int,input().split())
s=list(map(int,input().split()))
acum=[0 for i in range(n+3)]
acum[0]=s[0]
for i in range(1,n):
    acum[i]=acum[i-1]+s[i]
ans=0
for i in range(n):
    low=i;high=n-1;
    while low-high>1:
        mid=(low+high)//2
        if acum[mid]-acum[i-1]>m:
            high=mid
        else:
            low=mid
    if acum[high]-acum[i-1]<=m:
        ans=max(ans,high-i+1)
    else:
        ans=max(ans,low-i+1)

print(ans)


n,m=map(int,input().split())
s=list(map(int,input().split()))
acum=[0 for i in range(n+3)]
acum[0]=s[0]
for i in range(1,n):
    acum[i]=acum[i-1]+s[i]
ans=0
for i in range(n):
    low=i;high=n-1;
    while low-high>1:
        mid=(low+high)//2
        if acum[mid]-acum[i-1]>m:
            high=mid
        else:
            low=mid

    if acum[high]-acum[i-1]<=m:
        ans=max(ans,high-i+1)
    elif acum[low]-acum[i-1]<=m:
        ans=max(ans,low-i+1)

print(ans)


n,m=map(int,input().split())
s=list(map(int,input().split()))
acum=[0 for i in range(n+3)]
acum[0]=s[0]
for i in range(1,n):
    acum[i]=acum[i-1]+s[i]
ans=0
for i in range(n):
    low=i;high=n-1;
    while high-low>1:
        mid=(low+high)//2
        if acum[mid]-acum[i-1]>m:
            high=mid
        else:
            low=mid
    if acum[high]-acum[i-1]<=m:
        ans=max(ans,high-i+1)
    elif acum[low]-acum[i-1]<=m:
        ans=max(ans,low-i+1)

print(ans)


n,t=map(int,input().split())
a=list(map(int,input().split()))
mx=0
sum=0
c=0
j=0
for i in range(n):
    sum+=a[i]
    c+=1
    if sum<=t:
        mx=max(c,mx)
    while sum>=t:
        sum-=a[j]
        j+=1
        c-=1
print(mx)


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class CodeForces{
    static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer token;
    public static void main(String args[])throws Exception{
        int input= readInt();
        TreeSet<Card> set = new TreeSet<Card>();
        for (int i = 0; i < input; i++) {
            token();
            set.add(new Card(nextInt(),nextInt()));
        }
        int counter = 1;
        int ans = 0;

        Iterator<Card> itr = set.descendingIterator();
        while(itr.hasNext() && counter > 0 && counter < input){
            Card x = itr.next();
            ans += x.a;
            counter += x.b;
            counter--;
        }
        System.out.println(ans);
    }

    public static void token()throws Exception{
        token = new StringTokenizer(reader.readLine());
    }

    public static int nextInt() throws Exception{
        return Integer.parseInt(token.nextToken());
    }

    public static int readInt() throws Exception{
        return Integer.parseInt(reader.readLine());
    }
}

class Card implements Comparable{
    public int a;
    public int b;

    public Card(int a, int b) {
        this.a = a;
        this.b = b;

    }

    @Override
    public int compareTo(Object o) {
        Card that = (Card) o;
        if(this.b == that.b){
            return this.a - that.a;
        }
        return this.b - that.b;
    }

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class CodeForces{
    static BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
    static StringTokenizer token;
    public static void main(String args[])throws Exception{
        int input= readInt();
        Card [] set = new Card[input];
        for (int i = 0; i < input; i++) {
            token();
            set[i] = (new Card(nextInt(),nextInt()));
        }
        int counter = 1;
        int ans = 0;
        Arrays.sort(set);

        for (int i = input - 1; i >= 0 && counter > 0; i--) {
            Card x = set[i];
            ans += x.a;
            counter += x.b;
            counter--;
        }
        System.out.println(ans);
    }

    public static void token()throws Exception{
        token = new StringTokenizer(reader.readLine());
    }

    public static int nextInt() throws Exception{
        return Integer.parseInt(token.nextToken());
    }

    public static int readInt() throws Exception{
        return Integer.parseInt(reader.readLine());
    }
}

class Card implements Comparable{
    public int a;
    public int b;

    public Card(int a, int b) {
        this.a = a;
        this.b = b;

    }

    @Override
    public int compareTo(Object o) {
        Card that = (Card) o;
        if(this.b == that.b){
            return this.a - that.a;
        }
        return this.b - that.b;
    }

}


import java.util.*;
import java.io.*;
public class Tester {
	public static void main(String args[])
	{
		Scanner sc=new Scanner(System.in);
		int i,j,k,l=-1,m=1,n,o,p,t,count=1,max_end_here=1,max_so_far=1,sum=0,total=1,total1=1,temp;
		total=sc.nextInt();
		sc.nextLine();
		int arr[]=new int[total+1];
		int arr1[]=new int[total+1];
		for(i=1;i<=total;i++)
		{
			arr[i]=sc.nextInt();
			arr1[i]=sc.nextInt();
			sc.nextLine();
		}
		for(i=1;i<=total;i++)
		{
			for(j=1;j<=total-1;j++)
			{
				if(arr1[j+1]>arr1[j])
				{
					temp=arr1[j+1];
					arr1[j+1]=arr1[j];
					arr1[j]=temp;
					temp=arr[j+1];
					arr[j+1]=arr[j];
					arr[j]=temp;
				}
				else if(arr1[j+1]==arr1[j])
				{
					if(arr[j+1]>arr[j])
					{
						temp=arr1[j+1];
						arr1[j+1]=arr1[j];
						arr1[j]=temp;
						temp=arr[j+1];
						arr[j+1]=arr[j];
						arr[j]=temp;
					}
				}
			}
		}
		while(count>0&&total1<=total)
		{
			count--;
			count+=arr1[total1];
			sum+=arr[total1];
			total1++;
		}
		System.out.println(sum);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class codeforces {
	static class Pair implements Comparable<Pair> {
		int p, c;

		public Pair(int p, int c) {
			this.p = p;
			this.c = c;
		}

		@Override
		public int compareTo(Pair o) {
			if (this.c > o.c)
				return -1;
			if (this.c == o.c && this.p > o.p)
				return -1;
			if (this.c == o.c && this.p == o.p)
				return 0;
			return 1;
		}

	}

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(bf.readLine());
		Pair cards[] = new Pair[n];
		for (int i = 0; i < n; i++) {
			StringTokenizer st = new StringTokenizer(bf.readLine());
			cards[i] = new Pair(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
		}
		Arrays.sort(cards);
		int sum = 0;
		int counter = 1;
		int num = 0;
		for (int i = 0; i < counter && num < n ; i++) {
			counter += cards[i].c;
			sum += cards[i].p;
			num++;
		}
		System.out.println(sum);
	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.StringTokenizer;

public class codeforces {
	static class Pair implements Comparable<Pair> {
		int p, c;

		public Pair(int p, int c) {
			this.p = p;
			this.c = c;
		}

		@Override
		public int compareTo(Pair o) {
			if (this.c > o.c)
				return -1;
			if (this.c == o.c && this.p > o.p)
				return -1;
			if (this.c == o.c && this.p == o.p)
				return 0;
			return 1;
		}

	}

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int n = Integer.parseInt(bf.readLine());
		Pair cards[] = new Pair[n];
		for (int i = 0; i < n; i++) {
			StringTokenizer st = new StringTokenizer(bf.readLine());
			cards[i] = new Pair(Integer.parseInt(st.nextToken()), Integer.parseInt(st.nextToken()));
		}
		Arrays.sort(cards);
		int sum = 0;
		int counter = 1;
		int num = 0;
		for (int i = 0; i < counter && num < n ; i++) {
			counter += cards[i].c;
			sum += cards[i].p;
		}
		System.out.println(sum);
	}
}


import java.io.OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        PrintWriter out = new PrintWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }

    static class TaskB {
        public void solve(int testNumber, InputReader in, PrintWriter out) {
            int n = in.nextInt();
            Card[] cards = new Card[n];
            for (int i = 0; i < n; i++) {
                cards[i] = new Card(in.nextInt(), in.nextInt());
            }
            int res = 0;
            int can = 1;
            Arrays.sort(cards);
            for (int i = 0; i < n; i++) {
                can += cards[i].b;
                res += cards[i].a;
                can--;
                if (can == 0) {
                    break;
                }
            }
            out.println(res);
        }

    }

    static class Card implements Comparable<Card> {
        int a;
        int b;

        public Card(int a, int b) {
            this.a = a;
            this.b = b;
        }

        public int compareTo(Card o) {
            if (this.b != o.b)
                return Integer.compare(o.b, this.b);
            return Integer.compare(o.a, this.a);
        }

    }

    static class InputReader {
        public BufferedReader reader;
        public StringTokenizer tokenizer;

        public InputReader(InputStream stream) {
            reader = new BufferedReader(new InputStreamReader(stream), 32768);
            tokenizer = null;
        }

        public String next() {
            while (tokenizer == null || !tokenizer.hasMoreTokens()) {
                try {
                    tokenizer = new StringTokenizer(reader.readLine());
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }

        public int nextInt() {
            return Integer.parseInt(next());
        }

    }
}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io. IOException;

public class Main {

public static void main(String [] args) throws IOException {
    BufferedReader bf =new BufferedReader (new InputStreamReader (System.in));
        int n=Integer.parseInt(bf.readLine());
        int [] a=new int[n];
        int [] b=new int[n];
        for(int i=0;i<n;i++){
            String [] s2=bf.readLine().split(" ");
            a[i]=Integer.parseInt(s2[0]);
            b[i]=Integer.parseInt(s2[1]);
        }
        boolean flag=false;
    //  int n=7;
    //int []a={9,8,9,9,5,1,0};
    //  int []b={1,1,0,1,1,1,1};
        int index=0;
        int biggest=0;
        int counter=1;
        int res=0;
        for(int j=0;j<n;j++){
            biggest=0;
            flag=false;
            for(int i=0;i<n;i++){

                if((a[i]>biggest)&&(b[i]!=0)){
                    index=i;
                    biggest=a[i];
                    flag=true;
                }
            }
            if(flag==false){
                biggest=-1;
                for(int i=0;i<n;i++){
                    if(biggest<a[i]){
                        biggest=a[i];
                        index=i;
                    }
                }
            }
            if(biggest==-1)
                break;
                res=res+a[index];
                counter--;
                a[index]=-1;
                counter=counter+b[index];
                if(counter==0)
                    break;

        }
        System.out.println(res);
    }

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io. IOException;

public class Main {

public static void main(String [] args) throws IOException {
    BufferedReader bf =new BufferedReader (new InputStreamReader (System.in));
        int n=Integer.parseInt(bf.readLine());
        int [] a=new int[n];
        int [] b=new int[n];
        for(int i=0;i<n;i++){
            String [] s2=bf.readLine().split(" ");
            a[i]=Integer.parseInt(s2[0]);
            b[i]=Integer.parseInt(s2[1]);
        }
        boolean flag=false;
    //  int n=3;
    //  int []a={1,2,0};
    //  int []b={0,0,2};
        int index=0;
        int biggest=0;
        int counter=1;
        int res=0;
        for(int j=0;j<n;j++){
            for(int i=0;i<n;i++){
                flag=false;
                if((a[i]>=biggest)&&(b[i]!=0)){
                    index=i;
                    biggest=a[i];
                    flag=true;
                }
            }
            if(flag==false){
                biggest=-1;
                for(int i=0;i<n;i++){
                    if(biggest<a[i]){
                        biggest=a[i];
                        index=i;
                    }
                }
            }
            if(biggest==-1)
                break;
                res=res+a[index];
                counter--;
                a[index]=-1;
                counter=counter+b[index];
                if(counter==0)
                    break;

        }
        System.out.println(res);
    }

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io. IOException;

public class Main {

public static void main(String [] args) throws IOException {
    BufferedReader bf =new BufferedReader (new InputStreamReader (System.in));
        int n=Integer.parseInt(bf.readLine());
        int [] a=new int[n];
        int [] b=new int[n];
        for(int i=0;i<n;i++){
            String [] s2=bf.readLine().split(" ");
            a[i]=Integer.parseInt(s2[0]);
            b[i]=Integer.parseInt(s2[1]);
        }
        boolean flag=false;
    //  int n=3;
  //int []a={1,2,0};
    //  int []b={0,0,2};
        int index=0;
        int biggest=0;
        int counter=1;
        int res=0;
        for(int j=0;j<n;j++){
            biggest=0;
            flag=false;
            for(int i=0;i<n;i++){

                if((a[i]>=biggest)&&(b[i]!=0)){
                    index=i;
                    biggest=a[i];
                    flag=true;
                }
            }
            if(flag==false){
                biggest=-1;
                for(int i=0;i<n;i++){
                    if(biggest<a[i]){
                        biggest=a[i];
                        index=i;
                    }
                }
            }
            if(biggest==-1)
                break;
                res=res+a[index];
                counter--;
                a[index]=-1;
                counter=counter+b[index];
                if(counter==0)
                    break;

        }
        System.out.println(res);
    }

}


import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io. IOException;

public class combination {

public static void main(String [] args) throws IOException {
    BufferedReader bf =new BufferedReader (new InputStreamReader (System.in));
    //  int n=Integer.parseInt(bf.readLine());
    //  int [] a=new int[n];
    //  int [] b=new int[n];
    //  for(int i=0;i<n;i++){
    //      String [] s2=bf.readLine().split(" ");
    //      a[i]=Integer.parseInt(s2[0]);
    //      b[i]=Integer.parseInt(s2[1]);
    //  }
        boolean flag=false;
        int n=3;
   int []a={1,2,0};
        int []b={0,0,2};
        int index=0;
        int biggest=0;
        int counter=1;
        int res=0;
        for(int j=0;j<n;j++){
            biggest=0;
            flag=false;
            for(int i=0;i<n;i++){

                if((a[i]>=biggest)&&(b[i]!=0)){
                    index=i;
                    biggest=a[i];
                    flag=true;
                }
            }
            if(flag==false){
                biggest=-1;
                for(int i=0;i<n;i++){
                    if(biggest<a[i]){
                        biggest=a[i];
                        index=i;
                    }
                }
            }
            if(biggest==-1)
                break;
                res=res+a[index];
                counter--;
                a[index]=-1;
                counter=counter+b[index];
                if(counter==0)
                    break;

        }
        System.out.println(res);
    }

}


import java.io.*;
import java.util.*;
public class j
{
public static void main(String aa[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int l=1,i=0,k=0,j=0,t=0,n=0,p=0;
n=Integer.parseInt(b.readLine());
int d[];
int e[];
String s[];
d=new int[n];
e=new int[n];
s=new String[n];
for(i=0;i<n;i++)
{
s[i]=b.readLine();
StringTokenizer c=new StringTokenizer(s[i]);
d[i]=Integer.parseInt(c.nextToken());
e[i]=Integer.parseInt(c.nextToken());
}
for(j=0;j<n-1;j++)
{
for(i=j+1;i<n;i++)
{
if(e[j]<e[i])
{
t=e[i];
e[i]=e[j];
e[j]=t;
t=d[i];
d[i]=d[j];
d[j]=t;
}
}
}
for(i=0;i<n;i++)
if(e[i]==0)
{
p=i;
break;
}
for(j=p;j<n-1;j++)
{
for(i=j+1;i<n;i++)
{
if(d[j]<d[i])
{
t=d[i];
d[i]=d[j];
d[j]=t;
}
}
}
for(i=0;l!=0&&n!=0;i++)
{
k+=d[i];
l--;
n--;
l+=e[i];
}
System.out.print(k);
}
}


import java.io.*;
import java.util.*;
public class j
{
public static void main(String aa[])throws IOException
{
BufferedReader b=new BufferedReader(new InputStreamReader(System.in));
int l=1,i=0,k=0,j=0,t=0,n=0,p=0;
n=Integer.parseInt(b.readLine());
int d[];
int e[];
String s[];
d=new int[n];
e=new int[n];
s=new String[n];
for(i=0;i<n;i++)
{
s[i]=b.readLine();
StringTokenizer c=new StringTokenizer(s[i]);
d[i]=Integer.parseInt(c.nextToken());
e[i]=Integer.parseInt(c.nextToken());
}
for(j=0;j<n-1;j++)
{
for(i=j+1;i<n;i++)
{
if(e[j]<e[i])
{
t=e[i];
e[i]=e[j];
e[j]=t;
t=d[i];
d[i]=d[j];
d[j]=t;
}
}
}
for(i=0;i<n;i++)
if(e[i]==0)
{
p=i;
break;
}
for(j=p;j<n-1;j++)
{
for(i=j+1;i<n;i++)
{
if(d[j]<d[i])
{
t=d[i];
d[i]=d[j];
d[j]=t;
}
}
}
for(i=0;l!=0;i++)
{
k+=d[i];
l--;
l+=e[i];
}
System.out.print(k);
}
}


/*
* @Author: steve
* @Date:   2015-05-27 22:38:09
* @Last Modified by:   steve
* @Last Modified time: 2015-05-27 22:50:12
*/
import java.io.*;
import java.util.*;

public class Combination {
    public static void main(String[] args) throws Exception{
    	BufferedReader entrada = new BufferedReader(new InputStreamReader(System.in));
    	int n=Integer.parseInt(entrada.readLine());
    	ArrayList<point> puntos = new ArrayList<point>();
    	for(int i=0;i<n;i++){
    		String[] cads=entrada.readLine().split(" ");
    		int a=Integer.parseInt(cads[0]),b=Integer.parseInt(cads[1]);
    		puntos.add(new point(a,b));
    	}
    	Collections.sort(puntos);
    	int llevo=puntos.get(0).b;
    	int total=puntos.get(0).a;
    	int i=1;
    	while(llevo!=0 && i<n){
    		total+=puntos.get(i).a;
    		llevo--;
    		llevo+=puntos.get(i).b;
    		i++;
    	}
    	System.out.println(total);
    }
}

class point implements Comparable<point>{
	public int a,b;

	public point(int a,int b){
		this.a=a;
		this.b=b;
	}

	public int compareTo(point c){
		int aux = (b<c.b)?1:((b==c.b)?0:-1);
		return (aux!=0)?aux:((a<c.a)?1:((a==c.a)?0:-1));
	}

	public String toString(){
		return a+" "+b;
	}
}


import java.util.*;

public class main {
    static class Card{
        Card(Scanner sin){
                top = sin.nextInt();
                down = sin.nextInt();
            }

        int top;
        int down;
    };

    public static void main(String[] args){
        Scanner scan = new Scanner(System.in);

        int count = scan.nextInt();

        List<Card> cards = new ArrayList<Card>();

        for(int i = 0; i < count; ++i){
            Card tmp = new Card (scan);
            cards.add(tmp);
        }

       // Сортировка

        Collections.sort(cards, new Comparator<Card>(){
            @Override
                public int compare(Card o1, Card o2) {
                if(o1.down < o2.down)
                    return 1;
                if(o1.down > o2.down)
                    return -1;
                if(o1.top < o2.top)
                    return 1;
                if(o1.top > o2.top)
                    return -1;
                return 0;
            }
        });

        int sum_count = 0;
        int sum_cards = 1;

        for(int i = 0; i < cards.size(); ++i){
            --sum_cards;
            sum_cards += cards.get(i).down;
            sum_count += cards.get(i).top;
            if(sum_cards == 0)
                break;
        }

        System.out.println(sum_count);

    }
}


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Scanner;

public class Task155B {

	public static void main(String... args) throws NumberFormatException,
			IOException {
		Solution.main(System.in, System.out);
	}

	static class Pair<T1, T2> {
		T1 x;
		T2 y;

		public Pair(T1 x, T2 y) {
			this.x = x;
			this.y = y;
		}
	}

	static class Solution {

		public static void main(InputStream is, OutputStream os)
				throws NumberFormatException, IOException {
			PrintWriter pw = new PrintWriter(os);
			Scanner s = new Scanner(is);

			int n = s.nextInt();
			int retVal = 0;

			ArrayList<Pair<Integer, Integer>> cards = new ArrayList<>(n);

			cards.add(new Pair<Integer, Integer>(s.nextInt(), s.nextInt()));
			Collections.sort(cards, new Comparator<Pair<Integer, Integer>>() {

				@Override
				public int compare(Pair<Integer, Integer> arg0,
						Pair<Integer, Integer> arg1) {
					int retVal = -arg0.y.compareTo(arg1.y);
					if (retVal != 0) {
						return retVal;
					}
					return -arg0.x.compareTo(arg1.x);
				}

			});

			int movesLeft = 1;
			for (int i = 0; i < cards.size() && movesLeft >= 0; i++) {
				movesLeft += cards.get(i).y;
				retVal += cards.get(i).x;
			}

			pw.write("" + retVal);

			pw.flush();
			s.close();
		}
	}

}


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Scanner;

public class Task155B {

	public static void main(String... args) throws NumberFormatException,
			IOException {
		Solution.main(System.in, System.out);
	}

	static class Pair<T1, T2> {
		T1 x;
		T2 y;

		public Pair(T1 x, T2 y) {
			this.x = x;
			this.y = y;
		}
	}

	static class Solution {

		public static void main(InputStream is, OutputStream os)
				throws NumberFormatException, IOException {
			PrintWriter pw = new PrintWriter(os);
			Scanner s = new Scanner(is);

			int n = s.nextInt();
			int retVal = 0;

			ArrayList<Pair<Integer, Integer>> cards = new ArrayList<>(n);

			for (int i = 0; i < n; i++) {
				cards.add(new Pair<Integer, Integer>(s.nextInt(), s.nextInt()));
			}
			Collections.sort(cards, new Comparator<Pair<Integer, Integer>>() {

				@Override
				public int compare(Pair<Integer, Integer> arg0,
						Pair<Integer, Integer> arg1) {
					int retVal = -arg0.y.compareTo(arg1.y);
					if (retVal != 0) {
						return retVal;
					}
					return -arg0.x.compareTo(arg1.x);
				}

			});

			int movesLeft = 1;
			for (int i = 0; i < cards.size() && movesLeft > 0; i++, movesLeft--) {
				movesLeft += cards.get(i).y;
				retVal += cards.get(i).x;
			}

			pw.write("" + retVal);

			pw.flush();
			s.close();
		}
	}

}


import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Scanner;

public class Task155B {

	public static void main(String... args) throws NumberFormatException,
			IOException {
		Solution.main(System.in, System.out);
	}

	static class Pair<T1, T2> {
		T1 x;
		T2 y;

		public Pair(T1 x, T2 y) {
			this.x = x;
			this.y = y;
		}
	}

	static class Solution {

		public static void main(InputStream is, OutputStream os)
				throws NumberFormatException, IOException {
			PrintWriter pw = new PrintWriter(os);
			Scanner s = new Scanner(is);

			int n = s.nextInt();
			int retVal = 0;

			ArrayList<Pair<Integer, Integer>> cards = new ArrayList<>(n);

			for (int i = 0; i < n; i++) {
				cards.add(new Pair<Integer, Integer>(s.nextInt(), s.nextInt()));
			}
			Collections.sort(cards, new Comparator<Pair<Integer, Integer>>() {

				@Override
				public int compare(Pair<Integer, Integer> arg0,
						Pair<Integer, Integer> arg1) {
					int retVal = -arg0.y.compareTo(arg1.y);
					if (retVal != 0) {
						return retVal;
					}
					return -arg0.x.compareTo(arg1.x);
				}

			});

			int movesLeft = 1;
			for (int i = 0; i < cards.size() && movesLeft >= 0; i++) {
				movesLeft += cards.get(i).y;
				retVal += cards.get(i).x;
			}

			pw.write("" + retVal);

			pw.flush();
			s.close();
		}
	}

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;

public class Main6 {
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line = "";
        StringBuilder out = new StringBuilder();
        while ((line = in.readLine()) != null && line.length() != 0) {
            int ncards = Integer.parseInt(line);
            Card[] cards = new Card[ncards];
            for (int i = 0; i < ncards; i++) {
                int[] v = retInts(in.readLine());
                cards[i] = new Card(v[0], v[1]);
            }
            Arrays.sort(cards);
            int dis = 1, i = 0, sum = 0;
            while (dis > 0 && i<cards.length) {
                sum += cards[i].a;
                dis += cards[i++].b - 1;
            }
            out.append(sum+"\n");
        }
        System.out.print(out);
    }

    public static int[] retInts(String line) {
        String[] w = line.split(" ");
        int[] nums = new int[w.length];
        for (int i = 0; i < w.length; i++)
            nums[i] = Integer.parseInt(w[i]);
        return nums;
    }
}

class Card implements Comparable<Card> {
    int a, b;

    public Card(int a, int b) {
        this.a = a;
        this.b = b;
    }

    @Override
    public int compareTo(Card o) {
        if (this.b == o.b)
            return -this.a + o.a;
        return -this.b + o.b;
    }

}


import java.util.Arrays;
import java.util.Scanner;

public class Cards {

	public static void main(String[]args){
		Scanner sc=new Scanner(System.in);
	    int n=sc.nextInt();
	    int score=0;
	    int cards=1;
	    pair[]cardss=new pair[n];
	    for(int i=0;i<n;i++){
	    	int a=sc.nextInt();
	    	int b=sc.nextInt();
	    	cardss[i]=new pair(a,b);
	    }
	    Arrays.sort(cardss);

	for(int i=0;i<n;i++){
		if(cards==0)
			break;
		score+=cardss[i].x;
		cards+=cardss[i].y;
		cards--;
	}
	System.out.println(score);

	}

	static class pair implements Comparable{
	int x;
	int y;
	public pair(int x,int y){
		this.x=x;
		this.y=y;
	}
	@Override
	public int compareTo(Object a) {
		pair aa=(pair)a;
		if(aa.y>this.y)
			return 1;
		else if(this.y>aa.y)
			return -1;
		else if(this.x<aa.x)
			return 1;
		else if(this.x>aa.x)
			return -1;
		else return 0;
	}

	}
}


import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;

public class Task155B {

	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		int n = sc.nextInt();
		ArrayList<Integer> ap = new ArrayList<>();
		int bTot = 1;
		int aTot = 0;
		for (int i = 0; i < n; i++) {
			int aLoc = sc.nextInt();
			int bLoc = sc.nextInt();
			if (bLoc > 0) {
				bTot--;
				bTot += bLoc;
				aTot += aLoc;
			} else {
				ap.add(aLoc);
			}
		}
		sc.close();

		int[] a = new int[ap.size()];
		for (int i = 0; i < a.length; i++) {
			a[i] = ap.get(i);
		}
		Arrays.sort(a);
		if (a.length > 0) {
			int len = (bTot < a.length) ? bTot : a.length;
			for (int i = a.length - 1; i >= a.length - len; i--) {
				aTot += a[i];
			}
		}

		System.out.println(aTot);
	}
}


import java.lang.*;
import java.io.*;
import java.util.*;

public class Combination {

	public static void main(String[] args) throws java.lang.Exception {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskA solver = new TaskA();
		solver.solve(in, out);
		out.close();
	}
}

class TaskA {

	public void solve(InputReader in, PrintWriter out) {
		int n = in.nextInt(), m = 1;
		int[] a = new int[n];
		int i, j, k = 0;
		int p, q;
		int ans = 0;

		for (i=0; i<n; ++i) {
			p = in.nextInt();
			q = in.nextInt();
			if (q > 0) {
				ans += p;
				m += q - 1;
			} else {
				a[k++] = p;
			}
		}

		Arrays.sort(a, 0, k);
		j = Math.min(k, m);
		--k;
		while (j>0 && k>=0) {
			ans += a[k--];
			--j;
		}
		out.println(ans);
	}
}

class InputReader {
	public BufferedReader reader;
	public StringTokenizer tokenizer;

	public InputReader(InputStream stream) {
		reader = new BufferedReader(new InputStreamReader(stream), 32768);
		tokenizer = null;
	}

	public String next() {
		while (tokenizer==null || !tokenizer.hasMoreTokens()) {
			try {
				tokenizer = new StringTokenizer(reader.readLine());
			} catch (IOException e) {
				throw new RuntimeException(e);
			}
		}
		return tokenizer.nextToken();
	}

	public int nextInt() {
		return Integer.parseInt(next());
	}

	public long nextLong() {
		return Long.parseLong(next());
	}
}


import java.util.Scanner;

public class Main {
    public static void main(String ar[]) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        int a[] = new int[n], b[] = new int[n];
        for (int i = 0; i < n; i++) {
            a[i] = in.nextInt();
            b[i] = in.nextInt();
        }

        for (int i = 0; i < n; i++) {
            for (int j = 0; j < n; j++) {
                if (i == j)
                    continue;
                if (b[i] > b[j]) {
                    int temp = b[i];
                    b[i] = b[j];
                    b[j] = temp;

                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                } else if (b[i] == b[j] && a[i] > a[j]) {
                    int temp = b[i];
                    b[i] = b[j];
                    b[j] = temp;

                    temp = a[i];
                    a[i] = a[j];
                    a[j] = temp;
                }
            }
        }

        int rem = b[0], points = a[0], idx = 1;
        while (rem > 0 && idx < n) {
            points += a[idx];
            rem += b[idx] - 1;
            idx++;
        }
        System.out.println(points);
    }
}


import java.io.*;
import java.util.*;
public class div1c {

    /**
     * @param args
     * @throws IOException
     */
    static class Node implements Comparable<Node>{

        int point,increase;

        public Node(int x , int y){
            point=x;
            increase=y;
        }

        @Override
        public int compareTo(Node o) {
            if(o.increase>increase)return 1;

            if (o.increase==increase&&point<o.point) {
                return 1;
            }
            return -1;
        }

    }

    public static void main(String[] args) throws IOException {
        // TODO Auto-generated method stub
        BufferedReader k=new BufferedReader(new InputStreamReader(System.in));
        PrintWriter out = new PrintWriter(new OutputStreamWriter(System.out));
        int card=Integer.parseInt(k.readLine());
        Node[]array=new Node[card];
        for (int i = 0; i < array.length; i++) {
            StringTokenizer str=new StringTokenizer(k.readLine());
            int x=Integer.parseInt(str.nextToken());
            int y=Integer.parseInt(str.nextToken());
            array[i]=new Node(x, y);
        }
        Arrays.sort(array);
        int max=0,count=1;

        for (int i = 0; i < array.length; i++) {
            if (count==0) {
                break;
            }
            max+=array[i].point;
            count+=(array[i].increase-1);
        }
        out.println(max);

        out.close();
    }

}


import static java.lang.Math.*;
import static java.lang.System.currentTimeMillis;
import static java.lang.System.exit;
import static java.lang.System.arraycopy;
import static java.util.Arrays.sort;
import static java.util.Arrays.binarySearch;
import static java.util.Arrays.fill;

import java.util.*;
import java.io.*;

public class Main {

    public static void main(String[] args) throws IOException {
        new Main().run();
    }

    BufferedReader in;
    PrintWriter out;
    StringTokenizer st = new StringTokenizer("");

    private void run() throws IOException {
//      in = new BufferedReader(new FileReader("input.txt"));
//      out = new PrintWriter("output.txt");

        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(new OutputStreamWriter(System.out));

        solve();
        in.close();
        out.close();
    }

    class Pair implements Comparable<Pair>{
        int a,b;
        public Pair(int a, int b) {
            this.a = a;
            this.b = b;
        }
        public int compareTo(Pair o) {
            if(b != o.b)
                return -b + o.b;
            return -a + o.a;
        }

    }
    final int MAXN = 1001;
    Pair[] kart = new Pair[MAXN];
    int n;

    private void solve() throws IOException {
        n = nextInt();
        for(int i = 0; i < n; i++){
            kart[i] = new Pair(nextInt(), nextInt());
        }
        sort(kart,0,n);
        int step = 1;
        int answer = 0;
        int i = 0;
        while(step > 0 && i < n){
            answer += kart[i].a;
            step += kart[i].b - 1;
            i++;
        }
        out.println(answer);
    }

    String nextToken() throws IOException {
        while (!st.hasMoreTokens())
            st = new StringTokenizer(in.readLine());
        return st.nextToken();
    }
    int nextInt() throws IOException {
        return Integer.parseInt(nextToken());
    }
    long nextLong() throws IOException {
        return Long.parseLong(nextToken());
    }
    double nextDouble() throws IOException {
        return Double.parseDouble(nextToken());
    }
    String nextLine() throws IOException {
        st = new StringTokenizer("");
        return in.readLine();
    }
    boolean EOF() throws IOException {
        while (!st.hasMoreTokens()) {
            String s = in.readLine();
            if (s == null)
                return true;
            st = new StringTokenizer(s);
        }
        return false;
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author KHALED
 */
public class Combination
{
    public static void main(String[] args)
    {
        MyScanner scan=new MyScanner();
        int n=scan.nextInt();
        int[]mark=new int[n];
        int[]extra=new int[n];
        for (int i = 0; i < n; i++)
        {
            int k=scan.nextInt();
            int h=scan.nextInt();
            mark[i]=k;
            extra[i]=h;
        }
        if(n==1)
        {
            System.out.println(mark[0]);
            return;
        }
        for (int i = 0; i < n-1; i++)
        {
            for (int j = i+1; j < n; j++)
            {
                if(extra[j]>=extra[i]&&mark[j]>mark[i])
                {
                    int temp=extra[i];
                    extra[i]=extra[j];
                    extra[j]=temp;
                    temp=mark[i];
                    mark[i]=mark[j];
                    mark[j]=temp;
                }
                else if(extra[j]>extra[i])
                {
                    int temp=extra[i];
                    extra[i]=extra[j];
                    extra[j]=temp;
                    temp=mark[i];
                    mark[i]=mark[j];
                    mark[j]=temp;
                }
            }
        }
//        for (int i = 0; i < n; i++)
//        {
//            System.out.print(mark[i]+"  ");
//        }
        //System.out.println("");
        int out=0,count=1;
        for (int i = 0; i < count; i++)
        {
            if(i==n)
                break;
            out+=mark[i];
            count+=extra[i];
            //System.out.println(out+"  "+count);
        }
        System.out.println(out);
    }
}
class MyScanner
{
    static BufferedReader br;
    static StringTokenizer st;

    public MyScanner()
    {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next()
    {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author KHALED
 */
public class Combination
{
    public static void main(String[] args)
    {
        MyScanner scan=new MyScanner();
        int n=scan.nextInt();
        int[]mark=new int[n];
        int[]extra=new int[n];
        for (int i = 0; i < n; i++)
        {
            int k=scan.nextInt();
            int h=scan.nextInt();
            mark[i]=k;
            extra[i]=h;
        }
        for (int i = 0; i < n-1; i++)
        {
            for (int j = i+1; j < n; j++)
            {
                if(extra[j]>=extra[i]&&mark[j]>mark[i])
                {
                    int temp=extra[i];
                    extra[i]=extra[j];
                    extra[j]=temp;
                    temp=mark[i];
                    mark[i]=mark[j];
                    mark[j]=temp;
                }
                else if(extra[j]>extra[i])
                {
                    int temp=extra[i];
                    extra[i]=extra[j];
                    extra[j]=temp;
                    temp=mark[i];
                    mark[i]=mark[j];
                    mark[j]=temp;
                }
            }
        }
//        for (int i = 0; i < n; i++)
//        {
//            System.out.print(mark[i]+"  ");
//        }
        //System.out.println("");
        int out=0,count=1;
        for (int i = 0; i < count; i++)
        {
            out+=mark[i];
            count+=extra[i];
            //System.out.println(out+"  "+count);
        }
        System.out.println(out);
    }
}
class MyScanner
{
    static BufferedReader br;
    static StringTokenizer st;

    public MyScanner()
    {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next()
    {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author KHALED
 */
public class Combination
{
    public static void main(String[] args)
    {
        MyScanner scan=new MyScanner();
        int n=scan.nextInt();
        int[]mark=new int[n];
        int[]extra=new int[n];
        for (int i = 0; i < n; i++)
        {
            int k=scan.nextInt();
            int h=scan.nextInt();
            mark[i]=k;
            extra[i]=h;
        }
        if(n==1)
        {
            System.out.println(mark[0]);
            return;
        }
        for (int i = 0; i < n-1; i++)
        {
            for (int j = i+1; j < n; j++)
            {
                if(extra[j]>=extra[i]&&mark[j]>mark[i])
                {
                    int temp=extra[i];
                    extra[i]=extra[j];
                    extra[j]=temp;
                    temp=mark[i];
                    mark[i]=mark[j];
                    mark[j]=temp;
                }
                else if(extra[j]>extra[i])
                {
                    int temp=extra[i];
                    extra[i]=extra[j];
                    extra[j]=temp;
                    temp=mark[i];
                    mark[i]=mark[j];
                    mark[j]=temp;
                }
            }
        }
//        for (int i = 0; i < n; i++)
//        {
//            System.out.print(mark[i]+"  ");
//        }
        //System.out.println("");
        int out=0,count=1;
        for (int i = 0; i < count; i++)
        {
            out+=mark[i];
            count+=extra[i];
            //System.out.println(out+"  "+count);
        }
        System.out.println(out);
    }
}
class MyScanner
{
    static BufferedReader br;
    static StringTokenizer st;

    public MyScanner()
    {
        br = new BufferedReader(new InputStreamReader(System.in));
    }

    String next()
    {
        while (st == null || !st.hasMoreElements()) {
            try {
                st = new StringTokenizer(br.readLine());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return st.nextToken();
    }

    int nextInt() {
        return Integer.parseInt(next());
    }

    long nextLong() {
        return Long.parseLong(next());
    }

    double nextDouble() {
        return Double.parseDouble(next());
    }
}


import java.util.*;
import java.io.*;
import java.awt.Point;

public class p155B {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		int n = in.nextInt();
		Point[] parr = new Point[n];
		for(int i=0; i<n; ++i) parr[i] = new Point(in.nextInt(), in.nextInt());

		Arrays.sort(parr, new Comparator<Point>(){
			public int compare(Point a, Point b) {
				return a.y - b.y;
			}
		});

		int res = 0, count = 1;
		for(int i=n-1; i>=0 && count > 0; --i, --count) {
			res += parr[i].x;
			count += parr[i].y;
		}

		System.out.println(res);
	}
}