This is the hard version of the problem. The only difference is that in this version $n \leq 200000$. You can make hacks only if both versions of the problem are solved.

There are $n$ potions in a line, with potion $1$ on the far left and potion $n$ on the far right. Each potion will increase your health by $a_i$ when drunk. $a_i$ can be negative, meaning that potion will decrease will health.

You start with $0$ health and you will walk from left to right, from first potion to the last one. At each potion, you may choose to drink it or ignore it. You must ensure that your health is always non-negative.

What is the largest number of potions you can drink?


-----Input-----

The first line contains a single integer $n$ ($1 \leq n \leq 200000$) — the number of potions.

The next line contains $n$ integers $a_1$, $a_2$, ... ,$a_n$ ($-10^9 \leq a_i \leq 10^9$) which represent the change in health after drinking that potion.


-----Output-----

Output a single integer, the maximum number of potions you can drink without your health becoming negative.


-----Examples-----

Input
6
4 -4 1 -3 1 -3
Output
5


-----Note-----

For the sample, you can drink $5$ potions by taking potions $1$, $3$, $4$, $5$ and $6$. It is not possible to drink all $6$ potions because your health will go negative at some point

Difficulty: MEDIUM_HARD
Tags: Data structures

Greedy algorithms
Skill types: Data structures

Greedy algorithms

Starter code:

Solutions:
from __future__ import division, print_function
import math
import os
import sys
from fractions import *
from sys import *
from decimal import *
from io import BytesIO, IOBase
from itertools import accumulate, combinations, permutations, combinations_with_replacement, product
from collections import *
import timeit, time
M = 10 ** 9 + 7
import heapq
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

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

def out(var):
	sys.stdout.write(str(var))

def lis():
	return list(map(int, inp().split()))

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

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

def strsep():
	return map(str, inp().split())

def fsep():
	return map(float, inp().split())

def inpu():
	return int(inp())

def regularbracket(t):
	p = 0
	for i in t:
		if i == '(':
			p += 1
		else:
			p -= 1
		if p < 0:
			return False
	else:
		if p > 0:
			return False
		else:
			return True

def binarySearchcount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] <= key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def binarySearch(arr, n, key):
	left = 0
	right = n - 1
	while left <= right:
		mid = (right + left) // 2
		if arr[mid] == key:
			return mid
		if arr[mid] <= key:
			left = mid + 1
		else:
			right = mid - 1
	return -1

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

def reverse1(string):
	pp = ''
	for i in string[::-1]:
		pp += i
	if pp == string:
		return True
	return False

def reverse2(list1):
	l = []
	for i in list1[::-1]:
		l.append(i)
	if l == list1:
		return True
	return False

def mex(list1):
	p = max(list1) + 1
	for i in range(len(list1)):
		if list1[i] != i:
			p = i
			break
	return p

def sumofdigits(n):
	n = str(n)
	s1 = 0
	for i in n:
		s1 += int(i)
	return s1

def perfect_square(n):
	s = math.sqrt(n)
	if s == int(s):
		return True
	return False

def roman_number(x):
	if x > 15999:
		return
	value = [5000, 4000, 1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
	symbol = ['F', 'MF', 'M', 'CM', 'D', 'CD', 'C', 'XC', 'L', 'XL', 'X', 'IX', 'V', 'IV', 'I']
	roman = ''
	i = 0
	while x > 0:
		div = x // value[i]
		x = x % value[i]
		while div:
			roman += symbol[i]
			div -= 1
		i += 1
	return roman

def soretd(s):
	for i in range(1, len(s)):
		if s[i - 1] > s[i]:
			return False
	return True

def countRhombi(h, w):
	ct = 0
	for i in range(2, h + 1, 2):
		for j in range(2, w + 1, 2):
			ct += (h - i + 1) * (w - j + 1)
	return ct

def countrhombi2(h, w):
	return h * h // 4 * (w * w // 4)

def binpow(a, b):
	if b == 0:
		return 1
	else:
		res = binpow(a, b // 2)
	if b % 2 != 0:
		return res * res * a
	else:
		return res * res

def binpowmodulus(a, b, m):
	a %= m
	res = 1
	while b > 0:
		if b & 1:
			res = res * a % m
		a = a * a % m
		b >>= 1
	return res

def coprime_to_n(n):
	result = n
	i = 2
	while i * i <= n:
		if n % i == 0:
			while n % i == 0:
				n //= i
			result -= result // i
		i += 1
	if n > 1:
		result -= result // n
	return result

def luckynumwithequalnumberoffourandseven(x, n, a):
	if x >= n and str(x).count('4') == str(x).count('7'):
		a.append(x)
	elif x < 1000000000000.0:
		luckynumwithequalnumberoffourandseven(x * 10 + 4, n, a)
		luckynumwithequalnumberoffourandseven(x * 10 + 7, n, a)
	return a

def luckynum(x, l, r, a):
	if x >= l and x <= r:
		a.append(x)
	if x > r:
		a.append(x)
		return a
	if x < 10000000000.0:
		luckynum(x * 10 + 4, l, r, a)
		luckynum(x * 10 + 7, l, r, a)
	return a

def luckynuber(x, n, a):
	p = set(str(x))
	if len(p) <= 2:
		a.append(x)
	if x < n:
		luckynuber(x + 1, n, a)
	return a

def interact(type, x):
	if type == 'r':
		inp = input()
		return inp.strip()
	else:
		print(x, flush=True)

def findTrailingZeros(n):
	count = 0
	while n >= 5:
		n //= 5
		count += n
	return count

def mergeSort(arr):
	if len(arr) > 1:
		mid = len(arr) // 2
		L = arr[:mid]
		R = arr[mid:]
		mergeSort(L)
		mergeSort(R)
		i = j = k = 0
		while i < len(L) and j < len(R):
			if L[i] < R[j]:
				arr[k] = L[i]
				i += 1
			else:
				arr[k] = R[j]
				j += 1
			k += 1
		while i < len(L):
			arr[k] = L[i]
			i += 1
			k += 1
		while j < len(R):
			arr[k] = R[j]
			j += 1
			k += 1
res = set()

def solven(p, l, a, b, n):
	if p > n or l > 10:
		return
	if p > 0:
		res.add(p)
	solven(p * 10 + a, l + 1, a, b, n)
	solven(p * 10 + b, l + 1, a, b, n)

def subsetsUtil(A, subset, index, d):
	print(*subset)
	s = sum(subset)
	d.append(s)
	for i in range(index, len(A)):
		subset.append(A[i])
		subsetsUtil(A, subset, i + 1, d)
		subset.pop(-1)
	return d

def subsetSums(arr, l, r, d, sum=0):
	if l > r:
		d.append(sum)
		return
	subsetSums(arr, l + 1, r, d, sum + arr[l])
	subsetSums(arr, l + 1, r, d, sum)
	return d

def print_factors(x):
	factors = []
	for i in range(1, x + 1):
		if x % i == 0:
			factors.append(i)
	return factors

def calc(X, d, ans, D):
	if len(X) == 0:
		return
	i = X.index(max(X))
	ans[D[max(X)]] = d
	Y = X[:i]
	Z = X[i + 1:]
	calc(Y, d + 1, ans, D)
	calc(Z, d + 1, ans, D)

def factorization(n, l):
	c = n
	if prime(n) == True:
		l.append(n)
		return l
	for i in range(2, c):
		if n == 1:
			break
		while n % i == 0:
			l.append(i)
			n = n // i
	return l

def good(b):
	l = []
	i = 0
	while len(b) != 0:
		if b[i] < b[len(b) - 1 - i]:
			l.append(b[i])
			b.remove(b[i])
		else:
			l.append(b[len(b) - 1 - i])
			b.remove(b[len(b) - 1 - i])
	if l == sorted(l):
		return True
	return False

def generate(st, s):
	if len(s) == 0:
		return
	if s not in st:
		st.add(s)
		for i in range(len(s)):
			t = list(s).copy()
			t.remove(s[i])
			t = ''.join(t)
			generate(st, t)
	return

def largestincreasingsubsequence(A):
	l = [1] * len(A)
	sub = []
	for i in range(1, len(l)):
		for k in range(i):
			if A[k] < A[i]:
				sub.append(l[k])
		l[i] = 1 + max(sub, default=0)
	return max(l, default=0)

def findOR(nums, N):
	prefix_sum = 0
	result = 0
	for i in range(N):
		result |= nums[i]
		prefix_sum += nums[i]
		result |= prefix_sum
	return result

def OR(a, n):
	ans = a[0]
	for i in range(1, n):
		ans |= a[i]
	return ans

def toString(List):
	return ''.join(List)

def permute(a, l, r, p):
	if l == r:
		p.append(toString(a))
	else:
		for i in range(l, r + 1):
			(a[l], a[i]) = (a[i], a[l])
			permute(a, l + 1, r, p)
			(a[l], a[i]) = (a[i], a[l])

def squareRoot(number, precision):
	start = 0
	(end, ans) = (number, 1)
	while start <= end:
		mid = int((start + end) / 2)
		if mid * mid == number:
			ans = mid
			break
		if mid * mid < number:
			start = mid + 1
		else:
			end = mid - 1
	increment = 0.1
	for i in range(0, precision):
		while ans * ans <= number:
			ans += increment
		ans = ans - increment
		increment = increment / 10
	return ans

def countRectangles(l, w):
	squareSide = math.gcd(l, w)
	return int(l * w / (squareSide * squareSide))

def count_same_digit(L, R):
	tmp = 0
	ans = 0
	n = int(math.log10(R) + 1)
	for i in range(0, n):
		tmp = tmp * 10 + 1
		for j in range(1, 10):
			if L <= tmp * j and tmp * j <= R:
				ans += 1
	return ans

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

def Kclosest(arr, x, k, n, ans):
	l = findCrossOver(arr, 0, n - 1, x)
	r = l + 1
	count = 0
	if arr[l] == x:
		l -= 1
	while l >= 0 and r < n and (count < k):
		if x - arr[l] < arr[r] - x:
			ans.append(arr[l])
			l -= 1
		else:
			ans.append(arr[r])
			r += 1
		count += 1
	while count < k and l >= 0:
		ans.append(arr[l])
		l -= 1
		count += 1
	while count < k and r < n:
		ans.append(arr[r])
		r += 1
		count += 1
	return ans

def prime(n):
	if n <= 1:
		return False
	if n <= 3:
		return True
	if n % 2 == 0 or n % 3 == 0:
		return False
	for i in range(5, int(math.sqrt(n)) + 1, 2):
		if n % i == 0:
			return False
	return True

def calcSum(arr, n, k):
	l = []
	sum = 0
	for i in range(k):
		sum += arr[i]
	l.append(sum)
	for i in range(k, n):
		sum = sum - arr[i - k] + arr[i]
		l.append(sum)
	return l

def dfs(root, nodeVal, nodeConnection, visited):
	leftVal = nodeVal[root][0]
	rightVal = nodeVal[root][1]
	solution = []
	if nodeConnection[root]:
		visited.add(root)
		for i in nodeConnection[root]:
			if i not in visited:
				solution.append(dfs(i, nodeVal, nodeConnection, visited))
		leftMax = 0
		rightMax = 0
		for i in solution:
			(l, r) = i
			leftMax += max(abs(leftVal - l[0]) + l[1], abs(leftVal - r[0]) + r[1])
			rightMax += max(abs(rightVal - l[0]) + l[1], abs(rightVal - r[0]) + r[1])
		return ((leftVal, leftMax), (rightVal, rightMax))
	else:
		return ((leftVal, 0), (rightVal, 0))

def luckynumber(x, n, a):
	if x > 0:
		a.append(x)
	if x > 10 ** 9:
		return a
	elif x < 1000000000000.0:
		luckynumber(x * 10 + 4, n, a)
		luckynumber(x * 10 + 7, n, a)

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

def solve(n, A):
	PA = []
	cnt = 0
	ans = 0
	for i in range(n):
		if A[i] < 0:
			heapq.heappush(PA, A[i])
		ans = ans + A[i]
		if ans >= 0:
			cnt += 1
		while ans < 0:
			a = heapq.heappop(PA)
			ans = ans - a
	return cnt

def main():
	n = inpu()
	arr = lis()
	print(solve(n, arr))
main()


import heapq
n = int(input())
arr = list(map(int, input().split()))
sumi = 0
ans = []
for i in arr:
	sumi += i
	heapq.heappush(ans, i)
	while sumi < 0:
		sumi -= ans[0]
		heapq.heappop(ans)
print(len(ans))


import heapq

def sol(A):
	li = []
	h = 0
	count = 0
	for i in range(len(A)):
		if h + A[i] >= 0:
			count += 1
			h += A[i]
			if A[i] < 0:
				heapq.heappush(li, A[i])
		elif li and li[0] < A[i]:
			h -= li[0]
			h += A[i]
			heapq.heapreplace(li, A[i])
	return count
x = int(input())
A = list(map(int, input().split()))
print(sol(A))


import heapq
input()
b = list(map(int, input().split()))
(s, a) = (0, [])
for x in b:
	heapq.heappush(a, x)
	s += x
	while s < 0:
		s -= a[0]
		heapq.heappop(a)
print(len(a))


import heapq

def question3():
	N = int(input())
	arr = list(map(int, input().split()))
	k1 = []
	heapq.heapify(k1)
	sum_upto = 0
	count = 0
	for i in range(N):
		sum_upto += arr[i]
		if arr[i] < 0:
			heapq.heappush(k1, arr[i])
		if sum_upto < 0:
			m1 = heapq.heappop(k1)
			sum_upto -= m1
		else:
			count += 1
	return count
remained_test_cases = 1
while remained_test_cases > 0:
	print(question3())
	remained_test_cases -= 1


from heapq import heapify, heappop, heappush
n = int(input())
a = list(map(int, input().split()))
he = []
heapify(he)
count = 0
add = 0
for i in range(n):
	add += a[i]
	count += 1
	if a[i] < 0:
		heappush(he, a[i])
	while add < 0:
		value = heappop(he)
		add -= value
		count -= 1
print(count)


import heapq
n = int(input())
d = [int(p) for p in input().split()]
heap = []
health = 0
for item in d:
	health += item
	heapq.heappush(heap, item)
	if health < 0:
		health -= heapq.heappop(heap)
print(len(heap))


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase
from heapq import heappush, heappop
if sys.version_info[0] < 3:
	from __builtin__ import xrange as range
	from future_builtins import ascii, filter, hex, map, oct, zip
MOD = 10 ** 9 + 7
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')

def main():
	n = int(input())
	a = [*map(int, input().split())]
	d = 0
	s = 0
	h = []
	for i in range(n):
		if a[i] >= 0:
			d += 1
			s += a[i]
		elif s + a[i] < 0:
			if h and h[0] < a[i]:
				s -= heappop(h)
				heappush(h, a[i])
				s += a[i]
		else:
			d += 1
			heappush(h, a[i])
			s += a[i]
	print(d)
main()


import heapq

def func(i, num):
	count = 0
	total = 0
	heap = list()
	for i in range(n):
		count += a[i]
		total += 1
		heapq.heappush(heap, a[i])
		while count < 0:
			poison = heapq.heappop(heap)
			count -= poison
			total -= 1
	print(total)
n = int(input())
a = list(map(int, input().split()))
func(n - 1, 0)


from sys import stdin, stdout, setrecursionlimit
from math import floor, gcd, fabs, factorial, fmod, sqrt, inf, log, log2
from random import seed, randint
from datetime import datetime
from collections import defaultdict as dd, deque
from heapq import merge, heapify, heappop, heappush, nsmallest
from bisect import bisect_left as bl, bisect_right as br, bisect
from collections import defaultdict as dd
mod = pow(10, 9) + 7
mod2 = 998244353

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

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

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

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

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

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

def smp():
	return map(str, inp().split())

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

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

def remadd(x, y):
	return 1 if x % y else 0

def ceil(a, b):
	return (a + b - 1) // b

def def_value():
	return 0

def def_inf():
	return inf

def atoi(s, x='0'):
	return ord(s) - ord(x)

def inc(s, n=1):
	return chr((ord(s) - ord('a') + n) % 26 + ord('a'))

class XY:

	def __init__(self, x, y):
		self.x = x
		self.y = y

def rotate(a, b, c):
	ang = (b.y - a.y) * (c.x - b.x) - (b.x - a.x) * (c.y - b.y)
	if ang == 0:
		return 0
	else:
		return ang / abs(ang)

def phi(n):
	(res, p) = (n, 2)
	while p * p <= n:
		if n % p == 0:
			while n % p == 0:
				n = n // p
			res -= res // p
		p += 1
	if n > 1:
		res -= res // n
	return res
n = iinp()
a = lmp()
sum = 0
mn = []
heapify(mn)
for i in range(n):
	sum += a[i]
	heappush(mn, a[i])
	if sum < 0:
		sum -= heappop(mn)
print(len(mn))


from heapq import heapify, heappush, heappop

def T():
	return int(input())

def S():
	return str(input())

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

def M():
	return map(int, input().split(' '))
n = T()
heap = []
heapify(heap)
arr = A()
total = 0
count = 0
for i in arr:
	total += i
	heappush(heap, i)
	while total < 0:
		total -= heappop(heap)
print(len(heap))


import sys
import heapq
N = int(sys.stdin.readline())
arr = list(map(int, sys.stdin.readline().strip().split()))
ans = []
heapq.heapify(ans)
total = 0
for item in arr:
	total += item
	if total < 0:
		total -= heapq.heappushpop(ans, item)
	else:
		heapq.heappush(ans, item)
print(len(ans))


import heapq
n = int(input())
l = [int(x) for x in input().split()]
ans = 0
count = 0
x = []
heapq.heapify(x)
for i in range(n):
	ans += l[i]
	heapq.heappush(x, l[i])
	while ans < 0:
		ans = ans - heapq.heappop(x)
print(len(x))


from heapq import heappop, heappush, heapify
n = int(input())
a = list(map(int, input().split()))
heap = []
cnt = 0
ans = 0
for i in range(n):
	ans += a[i]
	cnt += 1
	if a[i] < 0:
		heappush(heap, a[i])
	if ans < 0:
		temp = -1 * heappop(heap)
		cnt -= 1
		ans += temp
print(cnt)


import sys
import io
import math
import collections
import decimal
import itertools
import bisect
import heapq

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

def main():
	N = int(input())
	A = list(map(int, input().split()))
	v = 0
	n = 0
	hq = []
	for a in A:
		if a >= 0:
			v += a
			n += 1
		elif v + a >= 0:
			v += a
			n += 1
			heapq.heappush(hq, a)
		else:
			p = heapq.heappushpop(hq, a)
			v += -p + a
	print(n)
main()


import heapq
n = int(input())
potions = list(map(int, input().split()))
hp = result = 0
poisons = []
for potion in potions:
	if potion >= 0:
		hp += potion
		result += 1
	elif hp + potion >= 0:
		hp += potion
		result += 1
		heapq.heappush(poisons, potion)
	else:
		if not poisons:
			continue
		if potion > poisons[0]:
			hp += potion - heapq.heappushpop(poisons, potion)
print(result)


n = int(input())
A = list(map(int, input().split()))
import heapq
cur = 0
prev = []
cnt = 0
for x in A:
	if x < 0:
		if cur + x >= 0:
			cur += x
			heapq.heappush(prev, x)
			cnt += 1
		elif prev and prev[0] < x:
			cur += x - prev[0]
			heapq.heappop(prev)
			heapq.heappush(prev, x)
	else:
		cur += x
		cnt += 1
print(cnt)


from math import *
from collections import defaultdict as dt
from sys import stdin
import heapq
inp = lambda : stdin.readline().strip()
I = lambda : int(inp())
M = lambda : map(int, inp().split())
L = lambda : list(M())
mod = 1000000007
inf = 100000000000000000000
ss = 'abcdefghijklmnopqrstuvwxyz'

def solve():
	n = I()
	a = L()
	(c, d, b) = (0, 0, [])
	heapq.heapify(b)
	for i in range(n):
		d = d + a[i]
		c += 1
		if a[i] < 0:
			heapq.heappush(b, a[i])
		if d < 0:
			d = d - heapq.heappop(b)
			c -= 1
	print(c)
tt = 1
for _ in range(tt):
	solve()


import heapq as h
n = int(input())
a = list(map(int, input().split()))
l = []
x = 0
for i in range(n):
	x = x + a[i]
	h.heappush(l, a[i])
	if x < 0:
		x = x - h.heappop(l)
print(len(l))


import heapq
n = int(input())
a = [int(d) for d in input().split()]
d = []
x = 0
for i in a:
	heapq.heappush(d, i)
	x = x + i
	if x < 0:
		c = heapq.heappop(d)
		x = x - c
print(len(d))


import math
import re
import sys
MOD = 1000000007
inp = lambda : map(int, input().split(' '))
ninp = lambda : int(input())
import heapq
n = ninp()
a = list(inp())
ans = list()
res = 0
for i in a:
	res += i
	heapq.heappush(ans, i)
	while res < 0:
		res -= ans[0]
		heapq.heappop(ans)
print(len(ans))


import sys
import heapq
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
pq = []
hp = 0
for x in a:
	heapq.heappush(pq, x)
	hp += x
	while hp < 0:
		hp -= heapq.heappop(pq)
print(len(pq))


import heapq
H = []
n = int(input())
for i in list(map(int, input().split())):
	tot = tot + i if 'tot' in locals() else i
	tot -= (heapq.heappush(H, i) if tot >= 0 else heapq.heappushpop(H, i)) or 0
print(len(H))


from sys import stdin
from heapq import *
input = stdin.readline

def solution():
	n = int(input())
	a = list(map(int, input().split()))
	answer = -1
	cur = 0
	hp = 0
	hq = []
	for k in a:
		if k >= 0:
			hp += k
			cur += 1
			answer = max(answer, cur)
		else:
			hp += k
			cur += 1
			heappush(hq, k)
			while hp < 0:
				x = heappop(hq)
				cur -= 1
				hp -= x
			answer = max(answer, cur)
	print(answer)
solution()


from heapq import heappop, heappush
n = int(input())
a = [int(x) for x in input().split()]
cnt = 0
health = 0
h = []
for i in a:
	health += i
	cnt += 1
	if i < 0:
		heappush(h, i)
	while health < 0 and h:
		health -= heappop(h)
		cnt -= 1
print(cnt)


import heapq
n = int(input())
arr = [int(num) for num in input().split()]
heap = []
s = 0
for num in arr:
	heapq.heappush(heap, num)
	s += num
	if s < 0:
		s -= heapq.heappop(heap)
print(len(heap))


import heapq

def solve():
	heap = []
	health = 0
	potions = 0
	for i in range(N):
		if A[i] >= 0:
			health += A[i]
			potions += 1
		elif health + A[i] >= 0:
			heapq.heappush(heap, A[i])
			health += A[i]
			potions += 1
		elif heap and heap[0] <= A[i]:
			bad_potion = heapq.heappop(heap)
			heapq.heappush(heap, A[i])
			health += A[i] - bad_potion
			assert health >= 0
	return potions
N = int(input())
A = list(map(int, input().split()))
print(solve())


from heapq import *
n = int(input())
a = list(map(int, input().split()))
b = []
heapify(b)
s = 0
ans = 0
for i in range(n):
	if a[i] >= 0:
		s += a[i]
		ans += 1
	elif s + a[i] >= 0:
		heappush(b, a[i])
		s += a[i]
		ans += 1
	elif b:
		s -= heappushpop(b, a[i])
		s += a[i]
	else:
		pass
print(ans)


def main():
	alpha = 'abcdefghijklmnopqrstuvwxyz'
	ALPHA = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
	inf = 1e+17
	mod = 10 ** 9 + 7

	def factorial(n):
		f = 1
		for i in range(1, n + 1):
			f = f * i % mod
		return f

	def ncr(n, r):
		num = den = 1
		for i in range(r):
			num = num * (n - i) % mod
			den = den * (i + 1) % mod
		return num * pow(den, mod - 2, mod) % mod

	def solve(n, arr):
		heap = []
		answer = n
		health = 0
		for i in range(n):
			if arr[i] >= 0:
				health += arr[i]
			elif health + arr[i] < 0:
				if heap:
					if heap[0] < arr[i]:
						health -= heapq.heappop(heap)
						health += arr[i]
						heapq.heappush(heap, arr[i])
				answer -= 1
				pass
			else:
				health += arr[i]
				heapq.heappush(heap, arr[i])
		return answer
		pass
	t = 1
	ans = []
	for _ in range(t):
		n = int(input())
		arr = [int(x) for x in input().split()]
		ans.append(solve(n, arr))
	for j in range(len(ans)):
		print(ans[j])
import sys, threading
import bisect
import math
import itertools
from sys import stdout
import heapq
from queue import PriorityQueue
input = sys.stdin.readline
thread = threading.Thread(target=main)
thread.start()
thread.join()


import heapq
n = int(input())
l = list(map(int, input().split()))
d = []
sum = 0
for i in l:
	sum += i
	heapq.heappush(d, i)
	if sum < 0:
		c = heapq.heappop(d)
		sum -= c
print(len(d))


import heapq
n = int(input())
lis = list(map(int, input().split()))
sumi = 0
neg = []
count = 0
for i in range(n):
	if sumi + lis[i] >= 0:
		count += 1
		sumi += lis[i]
		if lis[i] < 0:
			heapq.heappush(neg, lis[i])
	elif len(neg) != 0 and neg[0] < lis[i]:
		sumi -= heapq.heappop(neg)
		sumi += lis[i]
		heapq.heappush(neg, lis[i])
print(count)


import heapq
I = input
IN = lambda x: map(int, x.split())
L = lambda x: list(IN(x))
n = int(I())
a = L(I())
j = 0
d = []
s = 0
for i in a:
	s += i
	if s < 0:
		s -= heapq.heappushpop(d, i)
		j += 1
	elif i < 0:
		heapq.heappush(d, i)
print(n - j)


import calendar
from heapq import *
n = int(input())
inp = list(map(int, input().split()))
h = []
(ans, tot) = (0, 0)
for x in inp:
	tot += x
	heappush(h, x)
	while tot < 0:
		tot -= heappop(h)
print(len(h))


import heapq
n = int(input())
arr = list(map(int, input().split()))
H = []
tot = 0
for i in arr:
	tot += i
	heapq.heappush(H, i)
	while tot < 0:
		tot -= H[0]
		heapq.heappop(H)
print(len(H))


from heapq import *
from sys import stdin
input = stdin.readline
n = int(input())
lst = list(map(int, input().split()))
(hp, arr) = (0, [])
for i in lst:
	hp += i
	heappush(arr, i)
	if hp < 0:
		hp -= heappop(arr)
print(len(arr))


n = int(input())
arr = []
inp = input().split()
for i in inp:
	arr.append(int(i))
sum1 = 0
result = []
count = 0
import heapq
arr1 = []
for i in arr:
	sum1 += i
	count += 1
	if i < 0:
		heapq.heappush(arr1, i)
	if sum1 < 0:
		while sum1 < 0:
			s = heapq.heappop(arr1)
			sum1 -= s
			count -= 1
print(count)


from sys import maxsize, stdout, stdin, stderr
mod = int(1000000000.0 + 7)

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

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

def S():
	return input().strip()

def grid(r, c):
	return [lint() for i in range(r)]
from collections import defaultdict, Counter
import math
import bisect
from itertools import groupby

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

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

def check_prime(n):
	for i in range(2, int(n ** (1 / 2)) + 1):
		if not n % i:
			return False
	return True

def Bs(a, x):
	i = 0
	j = 0
	left = 0
	right = len(a)
	flag = False
	while left < right:
		mi = (left + right) // 2
		if a[mi] <= x:
			left = mi + 1
			i += 1
		else:
			right = mi
			j += 1
	if left > 0 and a[left - 1] == x:
		return (i - 1, j)
	else:
		return (-1, -1)
n = I()
s = lint()
from heapq import heappop, heappush
hp = []
ans = 0
tot = 0
for (i, a) in enumerate(s):
	tot += a
	heappush(hp, a)
	while hp and tot < 0:
		tot -= heappop(hp)
	ans = max(ans, len(hp))
print(ans)


import heapq
import sys
from math import *
import threading
from heapq import *
from itertools import count
from pprint import pprint
from collections import defaultdict
from heapq import heapify, heappop, heappush
sys.setrecursionlimit(300000)
mod = 10 ** 9 + 7
inf = 10 ** 15
decision = ['NO', 'YES']
yes = 'YES'
no = 'NO'
import os
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

def npr(n, r):
	return factorial(n) % mod // (factorial(n - r) % mod) if n >= r else 0

def ncr(n, r):
	return factorial(n) % mod // (factorial(r) % mod * (factorial(n - r) % mod)) if n >= r else 0

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

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

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

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

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

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

def SieveOfEratosthenes(n):
	prime = [{1, i} for i in range(n + 1)]
	p = 2
	while p <= n:
		for i in range(p * 2, n + 1, p):
			prime[i].add(p)
		p += 1
	return prime

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

def prod(li):
	ans = 1
	for i in li:
		ans *= i
	return ans

def sumk(a, b):
	print('called for', a, b)
	ans = a * (a + 1) // 2
	ans -= b * (b + 1) // 2
	return ans

def sumi(n):
	ans = 0
	if len(n) > 1:
		for x in n:
			ans += int(x)
		return ans
	else:
		return int(n)

def checkwin(x, a):
	if a[0][0] == a[1][1] == a[2][2] == x:
		return 1
	if a[0][2] == a[1][1] == a[2][0] == x:
		return 1
	if len(set(a[0])) == 1 and a[0][0] == x or (len(set(a[1])) == 1 and a[1][0] == x) or (len(set(a[2])) == 1 and a[2][0] == x):
		return 1
	if len(set(a[0][:])) == 1 and a[0][0] == x or (len(set(a[1][:])) == 1 and a[0][1] == x) or (len(set(a[2][:])) == 1 and a[0][0] == x):
		return 1
	return 0
karmanya = 1
while karmanya != 0:
	karmanya -= 1
	n = int(input())
	a = list(map(int, input().split()))
	s = 0
	mini = []
	heapq.heapify(mini)
	s = 0
	cnt = 0
	for i in range(n):
		if a[i] < 0:
			heapq.heappush(mini, a[i])
		if s + a[i] >= 0:
			s += a[i]
			cnt += 1
		else:
			s += a[i]
			s -= heapq.heappop(mini)
	print(cnt)


import sys
sys.setrecursionlimit(10 ** 5 + 1)
inf = int(10 ** 20)
max_val = inf
min_val = -inf
RW = lambda : sys.stdin.readline().strip()
RI = lambda : int(RW())
RMI = lambda : [int(x) for x in sys.stdin.readline().strip().split()]
RWI = lambda : [x for x in sys.stdin.readline().strip().split()]
import heapq
lens = RI()
arrs = RMI()
sum_now = 0
drop = []
heapq.heapify(drop)
for i in arrs:
	if i < 0:
		heapq.heappush(drop, i)
	sum_now += i
	if sum_now < 0:
		sum_now -= heapq.heappop(drop)
		lens -= 1
print(lens)


import heapq
n = int(input())
a = list(map(int, input().split()))
sol = []
heapq.heapify(sol)
lund = False
length = 0
limit = 20
farsi1 = 1234
farsi2 = 34
total = 0
count = 0
for i in a:
	total += i
	count += 1
	farsi1 = 12
	if i < 0:
		heapq.heappush(sol, i)
		farsi2 = 43
	while total < 0:
		t = heapq.heappop(sol)
		total += abs(t)
		count -= 1
	length += 1
	if length > 20:
		lund = True
print(count)


from heapq import heapify, heappush, heappop
n = int(input())
l = list(map(int, input().split()))
heap = []
heapify(heap)
ans = 0
a = 0
for i in range(n):
	a += l[i]
	ans += 1
	heappush(heap, l[i])
	while a < 0:
		a -= heappop(heap)
		ans -= 1
print(ans)


from heapq import heappush, heappop
heap = []
n = int(input())
arr = [int(x) for x in input().split()]
currsum = 0
for i in range(n):
	if currsum + arr[i] >= 0:
		heappush(heap, arr[i])
		currsum += arr[i]
	elif heap and arr[i] > heap[0]:
		currsum -= heappop(heap)
		heappush(heap, arr[i])
		currsum += arr[i]
print(len(heap))


from __future__ import division, print_function
import os
import sys
from io import BytesIO, IOBase

def main():
	pass
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

def print(*args, **kwargs):
	(sep, file) = (kwargs.pop('sep', ' '), kwargs.pop('file', sys.stdout))
	at_start = True
	for x in args:
		if not at_start:
			file.write(sep)
		file.write(str(x))
		at_start = False
	file.write(kwargs.pop('end', '\n'))
	if kwargs.pop('flush', False):
		file.flush()
if sys.version_info[0] < 3:
	(sys.stdin, sys.stdout) = (FastIO(sys.stdin), FastIO(sys.stdout))
else:
	(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
import heapq
n = int(input().rstrip())
list1 = list(map(int, input().rstrip().split()))
num1 = 0
list2 = []
sum1 = 0
i = 0
while i < len(list1):
	if sum1 + list1[i] < 0:
		if len(list2) == 0:
			i += 1
		else:
			t1 = heapq.heappop(list2)
			if t1 > list1[i]:
				i += 1
				heapq.heappush(list2, t1)
			else:
				sum1 -= t1
				num1 -= 1
	else:
		sum1 += list1[i]
		heapq.heappush(list2, list1[i])
		i += 1
		num1 += 1
print(num1)


import heapq
n = int(input())
potions = tuple(map(int, input().split()))
health = 0
res = 0
heap = []
for potion in potions:
	res += 1
	if potion < 0:
		heapq.heappush(heap, potion)
	health += potion
	if health < 0:
		health -= heapq.heappop(heap)
		res -= 1
print(res)


import math
import heapq

def solve():
	n = int(input())
	arr = list(map(int, input().strip().split()))
	for i in range(n):
		if arr[i] >= 0:
			arr = arr[i:n + 1]
			n = len(arr)
			break
	heap = []
	S = 0
	ans = 0
	for i in range(n):
		if arr[i] < 0:
			heapq.heappush(heap, arr[i])
		S += arr[i]
		ans += 1
		while S < 0:
			a = heapq.heappop(heap)
			ans -= 1
			S -= a
	return ans
print(solve())


import heapq
i = int(input())
(h, t) = ([], 0)
for x in list(map(int, input().split())):
	heapq.heappush(h, x)
	t += x
	while t < 0:
		t -= heapq.heappop(h)
print(len(h))


import math
import random
import heapq, bisect
import sys
from collections import deque, defaultdict
from fractions import Fraction
import sys
import threading
from collections import defaultdict
threading.stack_size(10 ** 8)
mod = 10 ** 9 + 7
mod1 = 998244353
import os
import sys
from io import BytesIO, IOBase
sys.setrecursionlimit(300000)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

class TreeNode:

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

class AvlTree:

	def __init__(self):
		self._tree = None

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

class SegmentTree1:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class SegmentTree:

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

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

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

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

	def __len__(self):
		return self._len

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

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

class Factorial:

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

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

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

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

class Combination:

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

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

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

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

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

def binarySearchCount(arr, n, key):
	left = 0
	right = n - 1
	count = 0
	while left <= right:
		mid = int((right + left) / 2)
		if arr[mid] < key:
			count = mid + 1
			left = mid + 1
		else:
			right = mid - 1
	return count

def countdig(n):
	c = 0
	while n > 0:
		n //= 10
		c += 1
	return c

def binary(x, length):
	y = bin(x)[2:]
	return y if len(y) >= length else '0' * (length - len(y)) + y

def countGreater(arr, n, k):
	l = 0
	r = n - 1
	leftGreater = n
	while l <= r:
		m = int(l + (r - l) / 2)
		if arr[m] >= k:
			leftGreater = m
			r = m - 1
		else:
			l = m + 1
	return n - leftGreater
for ik in range(1):
	n = int(input())
	l = list(map(int, input().split()))
	s = 0
	ans = 0
	e = []
	heapq.heapify(e)
	for i in range(n):
		s += l[i]
		heapq.heappush(e, l[i])
		ans += 1
		if s < 0:
			mi = heapq.heappop(e)
			s -= mi
			ans -= 1
	print(ans)


import os
import sys
from io import BytesIO, IOBase
from heapq import *

def main():
	n = int(input())
	a = list(map(int, input().split()))
	(b, ans, su) = ([], 0, 0)
	for i in range(n):
		su += a[i]
		if a[i] < 0:
			heappush(b, a[i])
		while su < 0:
			su -= b[0]
			heappop(b)
			ans += 1
	print(n - ans)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


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

def solve():
	summ = 0
	ans = []
	heapq.heapify(ans)
	count = 0
	for i in a:
		summ += i
		heapq.heappush(ans, i)
		if summ < 0:
			summ = summ - heapq.heappop(ans)
		else:
			count += 1
	print(count)
solve()


import heapq
n = int(input())
arr = list(map(int, input().split()))
pq = []
curr = 0
count = 0
for ele in arr:
	if ele >= 0:
		curr += ele
		count += 1
	elif curr + ele >= 0:
		curr += ele
		heapq.heappush(pq, ele)
		count += 1
	elif pq and pq[0] < ele:
		curr -= heapq.heappop(pq)
		heapq.heappush(pq, ele)
		curr += ele
print(count)


import heapq
n = int(input())
lis = list(map(int, input().split()))
l = list()
sum = 0
for i in lis:
	sum += i
	heapq.heappush(l, i)
	while sum < 0:
		sum -= heapq.heappop(l)
print(len(l))


n = int(input())
elems = [int(x) for x in input().split()]
potions = []
import heapq as heap
heap.heapify(potions)
life = 0
for i in elems:
	life += i
	heap.heappush(potions, i)
	if life < 0:
		life -= potions[0]
		heap.heappop(potions)
print(len(potions))


from sys import stdin, stdout
import math, bisect, heapq
from collections import Counter, deque, defaultdict
L = lambda : list(map(int, stdin.readline().strip().split()))
I = lambda : int(stdin.readline().strip())
S = lambda : stdin.readline().strip()
C = lambda : stdin.readline().strip().split()

def pr(a):
	return '.'.join(list(map(str, a)))

def solve():
	n = I()
	a = L()
	x = []
	s = 0
	heapq.heapify(x)
	for i in range(n):
		s += a[i]
		heapq.heappush(x, a[i])
		if s < 0:
			s -= heapq.heappop(x)
	print(len(x))
for _ in range(1):
	solve()


import sys
from sys import stdout
import io, os
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
P = lambda : list(map(int, input().split()))
from math import factorial as f
from collections import deque
from heapq import heapify, heappop, heappush, heappushpop, heapreplace, merge
mod = 10 ** 9 + 7
a = ord('a')

def fast_exp(x, exp):
	ans = 1
	base = x
	while exp:
		if exp & 1:
			ans *= base
		base *= base
		base %= mod
		ans %= mod
		exp >>= 1
	return ans

def solve():
	n = int(input())
	l = P()
	cap = 0
	currneg = 0
	ans = 0
	pq = []
	for i in l:
		if i >= 0:
			cap += i
			ans += 1
		elif currneg + abs(i) <= cap:
			heappush(pq, i)
			currneg += abs(i)
			ans += 1
		elif pq and pq[0] < i:
			currneg = currneg - abs(pq[0]) + abs(i)
			heappushpop(pq, i)
	print(ans)
solve()


import sys, heapq
input = sys.stdin.readline
n = int(input())
a = list(map(int, input().split()))
s = 0
l = []
ans = 0
for i in range(n):
	if a[i] >= 0:
		s += a[i]
		ans += 1
	elif s + a[i] >= 0:
		heapq.heappush(l, a[i])
		s += a[i]
		ans += 1
	elif len(l) > 0:
		if a[i] > l[0]:
			s += a[i] - l[0]
			heapq.heappop(l)
			heapq.heappush(l, a[i])
		else:
			continue
print(ans)


from heapq import *
n = int(input())
arr = list(map(int, input().split()))
h = []
heapify(h)
s = 0
for i in arr:
	s += i
	heappush(h, i)
	while s < 0:
		s -= h[0]
		heappop(h)
print(len(h))


import sys
import math
import heapq

def input():
	return sys.stdin.readline().strip('\n')

def I():
	return input()

def II():
	return int(input())

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

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

def isPerfectSquare(x):
	return int(math.sqrt(x)) ** 2 == x
n = II()
a = LI()
curr = 0
b = []
for i in range(n):
	curr += a[i]
	heapq.heappush(b, a[i])
	if curr < 0:
		x = heapq.heappop(b)
		curr -= x
print(len(b))


import heapq
n = int(input())
heap = []
s = 0
heapq.heapify(heap)
for i in list(map(int, input().split())):
	heapq.heappush(heap, i)
	s += i
	while s < 0:
		s -= heapq.heappop(heap)
print(len(heap))


import sys
import os.path
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
depth = 1000005
mod = 1000000007
lim = mod * mod
sys.setrecursionlimit(depth)
from math import inf, ceil, sqrt
from collections import defaultdict
from heapq import heappush, heappop, heapify
n = int(input())
a = list(map(int, input().split()))
h = list()
heapify(h)
(s, r) = (0, 0)
for e in a:
	if s + e >= 0:
		(r, s) = (r + 1, s + e)
		if e < 0:
			heappush(h, e)
	elif len(h) and h[0] < e:
		s -= heappop(h)
		heappush(h, e)
		s += e
print(r)


import sys
import heapq
n = int(sys.stdin.readline())
nums = list(map(int, sys.stdin.readline().split()))
su = 0
h = []
ans = 0
for i in nums:
	su += i
	heapq.heappush(h, i)
	if su < 0:
		su -= heapq.heappop(h)
	else:
		ans += 1
print(ans)


import sys
from heapq import heappop, heappush
n = int(sys.stdin.readline())
data = list(map(int, sys.stdin.readline().split()))
ans = []
cnt = 0
for item in data:
	cnt += item
	heappush(ans, item)
	if cnt < 0:
		temp = heappop(ans)
		cnt -= temp
print(len(ans))


import os
import sys
import math
from io import BytesIO, IOBase
from collections import deque, defaultdict, OrderedDict, Counter
from heapq import heappush, heappop, heapify
from bisect import bisect_right, insort, bisect_left
from functools import lru_cache
from itertools import permutations
sys.setrecursionlimit(10 ** 6)

def STRIN():
	return input()

def INTIN():
	return int(input())

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

def LSTR():
	return list(map(str, input().split()))

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

def MSTR():
	return map(str, input().split())

def solve(s):
	if s == s[::-1]:
		return True
	return False

def main():
	n = INTIN()
	l = LINT()
	(s, c) = (0, 0)
	h = []
	for i in range(n):
		if l[i] < 0:
			heappush(h, l[i])
			s += l[i]
			c += 1
		else:
			s += l[i]
			c += 1
		if s < 0:
			val = h[0]
			if val <= l[i]:
				s -= val
				c -= 1
				heappop(h)
			else:
				s += val
				c += 1
	print(c)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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


import heapq
n = int(input())
l = list(map(int, input().split()))
ans = []
s = 0
for i in range(n):
	s += l[i]
	heapq.heappush(ans, l[i])
	while s < 0:
		s -= ans[0]
		heapq.heappop(ans)
print(len(ans))


import heapq
n = int(input())
a = list(map(int, input().split()))
l = []
heapq.heapify(l)
cnt = 0
val = 0
for j in range(n):
	if a[j] >= 0:
		cnt += 1
		val += a[j]
	elif val + a[j] >= 0:
		heapq.heappush(l, a[j])
		cnt += 1
		val += a[j]
	elif len(l) > 0:
		v1 = heapq.heappop(l)
		if v1 < a[j]:
			heapq.heappush(l, a[j])
			val += -v1 + a[j]
		else:
			heapq.heappush(l, v1)
print(cnt)


import heapq
n = int(input())
w = [int(k) for k in input().split()]
c = []
res = 0
eta = 0
for j in range(n):
	if w[j] >= 0:
		eta += w[j]
		res += 1
	elif eta + w[j] >= 0:
		eta += w[j]
		res += 1
		heapq.heappush(c, w[j])
	elif c and w[j] > c[0]:
		eta -= heapq.heappop(c)
		eta += w[j]
		heapq.heappush(c, w[j])
print(res)


import sys
import math
mod = 10 ** 9 + 7
import heapq
LI = lambda : [int(k) for k in input().split()]
input = lambda : sys.stdin.readline().rstrip()
IN = lambda : int(input())
S = lambda : input()
r = range
n = int(input())
arr = LI()
li = []
heapq.heapify(li)
sm = 0
ans = 0
for i in arr:
	sm += i
	heapq.heappush(li, i)
	if sm >= 0:
		ans += 1
	else:
		sm -= heapq.heappop(li)
print(ans)


import heapq
n = int(input())
l = list(map(int, input().split()))
arr = l
heap = []
s = 0
count = 0
for i in range(len(arr)):
	s += arr[i]
	count += 1
	heapq.heappush(heap, arr[i])
	while s < 0:
		m = heapq.heappop(heap)
		s -= m
		count -= 1
print(count)


import heapq
n = int(input())
arr = [int(x) for x in input().split()]
H = []
total = 0
for i in arr:
	total += i
	heapq.heappush(H, i)
	while total < 0:
		total -= H[0]
		heapq.heappop(H)
print(len(H))


import heapq as hq
import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	a = list(map(int, input().split()))
	h = 0
	arr = []
	for i in range(n):
		h += a[i]
		hq.heappush(arr, a[i])
		while h < 0:
			h -= hq.heappop(arr)
	print(len(arr))
for _ in range(1):
	solve()


import heapq
n = int(input())
potion = list(map(int, input().split()))
(nowhp, ans) = (0, 0)
minheap = []
for i in range(n):
	if potion[i] >= 0:
		nowhp = nowhp + potion[i]
		ans = ans + 1
		continue
	elif nowhp + potion[i] >= 0:
		nowhp = nowhp + potion[i]
		ans = ans + 1
		heapq.heappush(minheap, potion[i])
		continue
	elif len(minheap) == 0 or potion[i] < minheap[0]:
		continue
	else:
		nowhp = nowhp - minheap[0] + potion[i]
		heapq.heappop(minheap)
		heapq.heappush(minheap, potion[i])
print(ans)


from sys import stdin, stdout
import math
import heapq
R = lambda : stdin.readline().strip()
RL = lambda f=None: list(map(f, R().split(' '))) if f else list(R().split(' '))
output = lambda x: stdout.write(str(x) + '\n')
output_list = lambda x: output(' '.join(map(str, x)))
n = int(R())
a = RL(int)
(sm_pos, sm_neg) = (0, 0)
hp = []
for i in a:
	if i < 0:
		heapq.heappush(hp, i)
		sm_neg += i
		while sm_neg + sm_pos < 0:
			t = heapq.heappop(hp)
			sm_neg -= t
	else:
		sm_pos += i
ans = sum([1 for i in a if i >= 0]) + len(hp)
print(ans)


import sys
import heapq
input = sys.stdin.readline
n = int(input())
l = list(map(int, input().split()))
h = []
heapq.heapify(h)
energy = 0
ans = 0
for i in l:
	if i >= 0:
		energy += i
		ans += 1
	elif energy + i < 0:
		if len(h) > 0:
			if h[0] < i:
				x = heapq.heappop(h)
				heapq.heappush(h, i)
				energy = energy + i - x
	else:
		energy += i
		heapq.heappush(h, i)
		ans += 1
print(ans)


import heapq
input()
H = []
total = 0
for i in list(map(int, input().split())):
	total += i
	total -= (heapq.heappush(H, i) if total >= 0 else heapq.heappushpop(H, i)) or 0
print(len(H))


from heapq import heapify, heappop, heappush
(n, a) = (int(input()), list(map(int, input().split())))
(res, cnt, total) = ([], 0, 0)
heapify(res)
for i in range(n):
	total += a[i]
	cnt += 1
	if a[i] < 0:
		heappush(res, a[i])
	while total < 0:
		tmp = heappop(res)
		total -= tmp
		cnt -= 1
print(cnt)


from bisect import bisect, bisect_left
from collections import *
from heapq import *
from math import gcd, ceil, sqrt, floor, inf, pi
from itertools import *
from operator import add, mul, sub, xor, truediv, floordiv
from functools import *
import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

def A(n):
	return [0] * n

def AI(n, x):
	return [x] * n

def A2(n, m):
	return [[0] * m for i in range(n)]

def G(n):
	return [[] for i in range(n)]

def GP(it):
	return [[ch, len(list(g))] for (ch, g) in groupby(it)]
from types import GeneratorType

def bootstrap(f, stack=[]):

	def wrappedfunc(*args, **kwargs):
		if stack:
			return f(*args, **kwargs)
		else:
			to = f(*args, **kwargs)
			while True:
				if type(to) is GeneratorType:
					stack.append(to)
					to = next(to)
				else:
					stack.pop()
					if not stack:
						break
					to = stack[-1].send(to)
			return to
	return wrappedfunc
mod = 10 ** 9 + 7
farr = [1]
ifa = []

def fact(x, mod=0):
	if mod:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr) % mod)
	else:
		while x >= len(farr):
			farr.append(farr[-1] * len(farr))
	return farr[x]

def ifact(x, mod):
	global ifa
	fact(x, mod)
	ifa.append(pow(farr[-1], mod - 2, mod))
	for i in range(x, 0, -1):
		ifa.append(ifa[-1] * i % mod)
	ifa.reverse()

def per(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return fact(i) // fact(i - j)
	return farr[i] * ifa[i - j] % mod

def com(i, j, mod=0):
	if i < j:
		return 0
	if not mod:
		return per(i, j) // fact(j)
	return per(i, j, mod) * ifa[j] % mod

def catalan(n):
	return com(2 * n, n) // (n + 1)

def isprime(n):
	for i in range(2, int(n ** 0.5) + 1):
		if n % i == 0:
			return False
	return True

def floorsum(a, b, c, n):
	if a == 0:
		return b // c * (n + 1)
	if a >= c or b >= c:
		return floorsum(a % c, b % c, c, n) + b // c * (n + 1) + a // c * n * (n + 1) // 2
	m = (a * n + b) // c
	return n * m - floorsum(c, c - b - 1, a, m - 1)

def inverse(a, m):
	a %= m
	if a <= 1:
		return a
	return (1 - inverse(m, a) * m) // a % m

def popcnt(x):
	ans = 0
	while x:
		ans += 1
		x &= x - 1
	return ans

def lowbit(n):
	return n & -n

class BIT:

	def __init__(self, arr):
		self.arr = arr
		self.n = len(arr) - 1

	def update(self, x, v):
		while x <= self.n:
			self.arr[x] += v
			x += x & -x

	def query(self, x):
		ans = 0
		while x:
			ans += self.arr[x]
			x &= x - 1
		return ans

class ST:

	def __init__(self, arr):
		n = len(arr)
		mx = n.bit_length()
		self.st = [[0] * mx for i in range(n)]
		for i in range(n):
			self.st[i][0] = arr[i]
		for j in range(1, mx):
			for i in range(n - (1 << j) + 1):
				self.st[i][j] = max(self.st[i][j - 1], self.st[i + (1 << j - 1)][j - 1])

	def query(self, l, r):
		if l > r:
			return -inf
		s = (r + 1 - l).bit_length() - 1
		return max(self.st[l][s], self.st[r - (1 << s) + 1][s])

class DSU:

	def __init__(self, n):
		self.c = [-1] * n

	def same(self, x, y):
		return self.find(x) == self.find(y)

	def find(self, x):
		if self.c[x] < 0:
			return x
		self.c[x] = self.find(self.c[x])
		return self.c[x]

	def union(self, u, v):
		(u, v) = (self.find(u), self.find(v))
		if u == v:
			return False
		if self.c[u] > self.c[v]:
			(u, v) = (v, u)
		self.c[u] += self.c[v]
		self.c[v] = u
		return True

	def size(self, x):
		return -self.c[self.find(x)]

class UFS:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv

class UF:

	def __init__(self, n):
		self.parent = [i for i in range(n)]
		self.ranks = [0] * n
		self.size = AI(n, 1)
		self.edge = A(n)

	def find(self, x):
		if x != self.parent[x]:
			self.parent[x] = self.find(self.parent[x])
		return self.parent[x]

	def union(self, u, v):
		(pu, pv) = (self.find(u), self.find(v))
		if pu == pv:
			self.edge[pu] += 1
			return False
		if self.ranks[pu] >= self.ranks[pv]:
			self.parent[pv] = pu
			self.edge[pu] += self.edge[pv] + 1
			self.size[pu] += self.size[pv]
			if self.ranks[pv] == self.ranks[pu]:
				self.ranks[pu] += 1
		else:
			self.parent[pu] = pv
			self.edge[pv] += self.edge[pu] + 1
			self.size[pv] += self.size[pu]

def Prime(n):
	c = 0
	prime = []
	flag = [0] * (n + 1)
	for i in range(2, n + 1):
		if not flag[i]:
			prime.append(i)
			c += 1
		for j in range(c):
			if i * prime[j] > n:
				break
			flag[i * prime[j]] = prime[j]
			if i % prime[j] == 0:
				break
	return flag

def dij(s, graph):
	d = AI(n, inf)
	d[s] = 0
	heap = [(0, s)]
	vis = A(n)
	while heap:
		(dis, u) = heappop(heap)
		if vis[u]:
			continue
		vis[u] = 1
		for (v, w) in graph[u]:
			if d[v] > d[u] + w:
				d[v] = d[u] + w
				heappush(heap, (d[v], v))
	return d

def bell(s, g):
	dis = AI(n, inf)
	dis[s] = 0
	for i in range(n - 1):
		for (u, v, w) in edge:
			if dis[v] > dis[u] + w:
				dis[v] = dis[u] + w
	change = A(n)
	for i in range(n):
		for (u, v, w) in edge:
			if dis[v] > dis[u] + w:
				dis[v] = dis[u] + w
				change[v] = 1
	return dis

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

def lis(nums):
	res = []
	for k in nums:
		i = bisect.bisect_left(res, k)
		if i == len(res):
			res.append(k)
		else:
			res[i] = k
	return len(res)

def RP(nums):
	n = len(nums)
	s = set(nums)
	d = {}
	for (i, k) in enumerate(sorted(s), 1):
		d[k] = i
	bi = BIT([0] * (len(s) + 1))
	ans = 0
	for i in range(n - 1, -1, -1):
		ans += bi.query(d[nums[i]] - 1)
		bi.update(d[nums[i]], 1)
	return ans

def michange(a, b):
	d = defaultdict(deque)
	for (i, x) in enumerate(b):
		d[x].append(i)
	order = A(len(a))
	for (i, x) in enumerate(a):
		if not d:
			return -1
		order[i] = d[x].popleft()
	return RP(order)

class DLN:

	def __init__(self, val):
		self.val = val
		self.pre = None
		self.next = None

def nb(i, j, n, m):
	for (ni, nj) in [[i + 1, j], [i - 1, j], [i, j - 1], [i, j + 1]]:
		if 0 <= ni < n and 0 <= nj < m:
			yield (ni, nj)

def topo(n):
	q = deque()
	res = []
	for i in range(1, n + 1):
		if ind[i] == 0:
			q.append(i)
			res.append(i)
	while q:
		u = q.popleft()
		for v in g[u]:
			ind[v] -= 1
			if ind[v] == 0:
				q.append(v)
				res.append(v)
	return res

@bootstrap
def gdfs(r, p):
	for ch in g[r]:
		if ch != p:
			yield gdfs(ch, r)
	yield None
t = 1
for i in range(t):
	n = N()
	a = RLL()
	reg = []
	cur = 0
	ans = 0
	for x in a:
		if x >= 0:
			cur += x
			ans += 1
		else:
			cur += x
			ans += 1
			heappush(reg, x)
			if cur < 0:
				mi = heappop(reg)
				cur -= mi
				ans -= 1
	print(ans)


from sys import stdin, stdout, setrecursionlimit
input = stdin.readline
inf = float('inf')
from functools import cmp_to_key
from collections import defaultdict as dd
from collections import Counter, deque
from heapq import *
import math
from math import floor, ceil, sqrt

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

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

def getis():
	return map(str, input().strip().split())

def getls():
	return list(map(str, input().strip().split()))

def gets():
	return input().strip()

def geta():
	return int(input())

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

def solve():
	n = geta()
	a = getl()
	heap = []
	ans = 0
	for i in a:
		heappush(heap, i)
		ans += i
		while ans < 0 and heap:
			now = heappop(heap)
			ans -= now
	print(len(heap))
solve()


import heapq
n = int(input())
potions = list(map(int, input().split()))
minH = []
health = 0
res = 0
for p in potions:
	health += p
	if health >= 0:
		res += 1
	if p >= 0:
		continue
	heapq.heappush(minH, p)
	if health < 0:
		min_val = heapq.heappop(minH)
		health -= min_val
print(res)


from sys import stdin
import heapq
n = int(stdin.readline())
a = list(map(int, stdin.readline().split()))
k = []
for i in a:
	tot = tot + i if 'tot' in locals() or 'tot' in globals() else i
	tot -= (heapq.heappush(k, i) if tot >= 0 else heapq.heappushpop(k, i)) or 0
print(len(k))


import heapq
import sys

def solve(l):
	(c, s) = (0, 0)
	k = []
	heapq.heapify(k)
	for i in range(len(l)):
		if l[i] >= 0:
			s = s + l[i]
			c = c + 1
		else:
			heapq.heappush(k, l[i])
			s = s + l[i]
			c = c + 1
			while s < 0:
				s = s - heapq.heappop(k)
				c = c - 1
	return c
n = int(sys.stdin.readline())
l = list(map(int, sys.stdin.readline().split()))
print(solve(l))


from collections import defaultdict
import heapq
from sys import stdin
input = stdin.readline

def f(a):
	s = 0
	q = []
	for i in a:
		s += i
		heapq.heappush(q, i)
		if s < 0:
			l = heapq.heappop(q)
			s -= l
	return len(q)
a = input()
lst = list(map(int, input().strip().split()))
print(f(lst))


import sys
input = lambda : sys.stdin.readline().rstrip('\r\n')
inp = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
mod = 10 ** 9 + 7
Mod = 998244353
INF = float('inf')
from math import *
from bisect import *
from heapq import *
from collections import defaultdict as dd
from collections import OrderedDict as odict
from collections import Counter as cc
from collections import deque
from itertools import groupby
sys.setrecursionlimit(20 * 20 * 20 * 20 + 10)
MAX = 10 ** 5

def solve():
	n = takein()
	arr = takeiar()
	sum = 0
	heap = []
	count = 0
	for i in arr:
		if i < 0:
			heappush(heap, i)
		sum += i
		count += 1
		while sum < 0:
			sum += abs(heappop(heap))
			count -= 1
	print(count)
	return

def main():
	global tt
	if not ONLINE_JUDGE:
		sys.stdin = open('input.txt', 'r')
		sys.stdout = open('output.txt', 'w')
	t = 1
	for tt in range(1, t + 1):
		solve()
	if not ONLINE_JUDGE:
		print('Time Elapsed :', time.time() - start_time, 'seconds')
		sys.stdout.close()

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

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

def takeiar():
	return list(map(int, sys.stdin.readline().rstrip('\r\n').split()))

def takesar():
	return list(map(str, sys.stdin.readline().rstrip('\r\n').split()))

def takeivr():
	return map(int, sys.stdin.readline().rstrip('\r\n').split())

def takesvr():
	return map(str, sys.stdin.readline().rstrip('\r\n').split())

def ispalindrome(s):
	return s == s[::-1]

def invert(bit_s):
	temp = int(bit_s, 2)
	inverse_s = temp ^ 2 ** (len(bit_s) + 1) - 1
	rslt = bin(inverse_s)[3:]
	return str(rslt)

def counter(a):
	q = [0] * max(a)
	for i in range(len(a)):
		q[a[i] - 1] = q[a[i] - 1] + 1
	return q

def counter_elements(a):
	q = dict()
	for i in range(len(a)):
		if a[i] not in q:
			q[a[i]] = 0
		q[a[i]] = q[a[i]] + 1
	return q

def string_counter(a):
	q = [0] * 26
	for i in range(len(a)):
		q[ord(a[i]) - 97] = q[ord(a[i]) - 97] + 1
	return q

def factorial(n, m=1000000007):
	q = 1
	for i in range(n):
		q = q * (i + 1) % m
	return q

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

def prime_factors(n):
	q = []
	while n % 2 == 0:
		q.append(2)
		n = n // 2
	for i in range(3, int(n ** 0.5) + 1, 2):
		while n % i == 0:
			q.append(i)
			n = n // i
	if n > 2:
		q.append(n)
	return list(sorted(q))

def transpose(a):
	(n, m) = (len(a), len(a[0]))
	b = [[0] * n for i in range(m)]
	for i in range(m):
		for j in range(n):
			b[i][j] = a[j][i]
	return b

def power_two(x):
	return x and (not x & x - 1)

def ceil(a, b):
	return -(-a // b)

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

def isprime(n):
	if n > 2 and (not n % 2) or n == 1:
		return False
	for i in range(3, int(n ** 0.5 + 1), 2):
		if not n % i:
			return False
	return True
ONLINE_JUDGE = __debug__
if ONLINE_JUDGE:
	input = sys.stdin.readline
main()


from heapq import *
n = int(input())
a = [int(x) for x in input().split()]
h = []
S = 0
for x in a:
	S += x
	heappush(h, x)
	while S < 0:
		S -= heappop(h)
print(len(h))


import sys, os
from io import BytesIO, IOBase
from functools import lru_cache
mod = 10 ** 9 + 7
Mod = 998244353
INF = float('inf')
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')
inp = lambda : list(map(int, sys.stdin.readline().rstrip('\r\n').split()))
from heapq import *
tc = 1
for test in range(1, tc + 1):
	n = int(input())
	a = inp()
	h = []
	ans = 0
	for i in range(n):
		if ans + a[i] >= 0:
			heappush(h, a[i])
			ans += a[i]
		elif h and h[0] < a[i]:
			val = heappop(h)
			heappush(h, a[i])
			ans += a[i] - val
	print(len(h))


import heapq
n = int(input())
nums = list(map(int, input().split()))
pq = []
total = 0
ans = 0
for num in nums:
	if num + total >= 0:
		total += num
		ans += 1
		if num < 0:
			heapq.heappush(pq, num)
	elif len(pq) > 0 and -num < -pq[0]:
		total -= pq[0]
		total += num
		heapq.heappop(pq)
		heapq.heappush(pq, num)
print(ans)


import heapq

def func():
	n = int(input())
	l = list(map(int, input().split()))
	pois = 0
	health = 0
	neg_pos = []
	heapq.heapify(neg_pos)
	for potion in l:
		if potion >= 0:
			pois += 1
			health += potion
		elif potion + health >= 0:
			pois += 1
			health += potion
			heapq.heappush(neg_pos, potion)
		elif neg_pos:
			mn = neg_pos[0]
			if potion > mn:
				health = health - mn + potion
				heapq.heapreplace(neg_pos, potion)
	return pois
t = 1
for i in range(t):
	print(func())


import os, sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')
(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
input = lambda : sys.stdin.readline().rstrip('\r\n')
mod = 998244353
from math import ceil, gcd
from bisect import bisect_right, bisect_left
from _collections import deque
import heapq
n = int(input())
a = list(map(int, input().split()))
ans = []
heapq.heapify(ans)
tot = 0
ct = 0
for i in a:
	tot += i
	ct += 1
	if i < 0:
		heapq.heappush(ans, i)
	while tot < 0:
		t = heapq.heappop(ans)
		tot += abs(t)
		ct -= 1
print(ct)


import heapq
n = int(input())
p = list(map(int, input().split()))
c = []
s = 0
for i in range(n):
	heapq.heappush(c, p[i])
	s += p[i]
	if s < 0:
		l = heapq.heappop(c)
		s -= l
print(len(c))


from heapq import heappush, heappushpop
n = int(input())
a = list(map(int, input().split()))
cnt = 0
x = 0
h = []
for d in a:
	if d >= 0:
		x += d
		cnt += 1
		continue
	if x + d >= 0:
		x += d
		cnt += 1
		heappush(h, d)
	elif h:
		y = heappushpop(h, d)
		x += d - y
print(cnt)


import heapq
q = []
n = int(input())
ar = list(map(int, input().split()))
health = 0
cnt = 0
for v in ar:
	if v >= 0:
		cnt += 1
		health += v
	elif health + v >= 0:
		cnt += 1
		heapq.heappush(q, v)
		health += v
	elif q:
		t = heapq.heappop(q)
		if t < v:
			health -= t
			health += v
			heapq.heappush(q, v)
		else:
			heapq.heappush(q, t)
print(cnt)


import heapq
n = int(input())
arr = list(map(int, input().split()))
heap = []
heapq.heapify(heap)
mxm = 0
count = 0
for i in arr:
	heapq.heappush(heap, i)
	mxm += i
	if mxm >= 0:
		count += 1
	elif mxm < 0:
		val = heapq.heappop(heap)
		mxm += abs(val)
print(count)


import heapq as hp
n = int(input())
arr = list(map(int, input().split()))
s = 0
res = []
hp.heapify(res)
for i in arr:
	if i < 0:
		hp.heappush(res, i)
	s += i
	if s < 0:
		s -= hp.heappop(res)
		n -= 1
print(n)


from heapq import heappop
import os.path
from math import gcd, floor, ceil
from collections import *
import sys
from heapq import *
mod = 1000000007
INF = float('inf')

def st():
	return list(sys.stdin.readline().strip())

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

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

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

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

def prl(n):
	return sys.stdout.write(str(n) + ' ')
if os.path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')

def solve():
	n = inp()
	l = li()
	h = []
	(cur, ans) = (0, 0)
	for i in l:
		cur += i
		ans += 1
		if i < 0:
			heappush(h, i)
		if cur < 0:
			cur -= heappop(h)
			ans -= 1
	pr(ans)
for _ in range(1):
	solve()


n = int(input())
a = list(map(int, input().split()))
import heapq
l = []
heapq.heapify(l)
ans = 0
s = 0
for i in range(0, len(a)):
	if a[i] < 0:
		heapq.heappush(l, a[i])
	s += a[i]
	if s < 0:
		ans += 1
		k = heapq.heappop(l)
		s -= k
print(len(a) - ans)


import math
import sys
import heapq
input = sys.stdin.readline

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

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

def insr():
	s = input().strip()
	return list(s[:len(s)])

def invr():
	return map(int, input().split())
n = inp()
l = inlt()
v = []
sm = 0
ln = 0
for i in range(n):
	if l[i] >= 0:
		ln += 1
		sm += l[i]
	elif sm + l[i] >= 0:
		sm += l[i]
		heapq.heappush(v, l[i])
	elif v:
		s = heapq.heappop(v)
		if s < l[i] and sm + l[i] - s >= 0:
			heapq.heappush(v, l[i])
			sm += l[i] - s
		else:
			heapq.heappush(v, s)
print(ln + len(v))


from heapq import heappush, heappop
n = int(input())
arr = list(map(int, input().split()))
c = 0
count = 0
heap = []
for i in arr:
	if i < 0:
		heappush(heap, i)
	c += i
	count += 1
	if c < 0:
		c -= heappop(heap)
		count -= 1
print(count)


import heapq
t = int(input())
a_list = [int(k) for k in input().split()]
heap = []
health = 0
res = 0
for v in a_list:
	health += v
	res += 1
	heapq.heappush(heap, v)
	while health < 0:
		health -= heapq.heappop(heap)
		res -= 1
print(len(heap))


import heapq
n = int(input())
arr = [int(x) for x in input().split()]
v = []
heapq.heapify(v)
count = 0
s = 0
for i in range(n):
	if count + arr[i] < 0:
		if len(v) == 0:
			continue
		x = heapq.heappop(v)
		if x < arr[i]:
			count -= x
			count += arr[i]
			heapq.heappush(v, arr[i])
		else:
			heapq.heappush(v, x)
	else:
		count += arr[i]
		heapq.heappush(v, arr[i])
		s += 1
print(s)


import sys
import heapq

def main():
	size = int(sys.stdin.readline().split()[0])
	a = [int(x) for x in sys.stdin.readline().split()]
	heap = []
	tot = 0
	health = 0
	for num in a:
		if num >= 0:
			tot += 1
			health += num
		else:
			newHealth = health + num
			if newHealth >= 0:
				tot += 1
				health = newHealth
				heapq.heappush(heap, num)
			elif len(heap) == 0 or num < heap[0]:
				continue
			else:
				removed = heapq.heappop(heap)
				heapq.heappush(heap, num)
				health -= removed
				health += num
	print(tot)
main()


import heapq
heap = []
n = int(input())
arr = list(map(int, input().split()))
sum1 = 0
count = 0
for i in range(n):
	sum1 += arr[i]
	heapq.heappush(heap, arr[i])
	count += 1
	while sum1 < 0:
		ele = heapq.heappop(heap)
		sum1 -= ele
		count -= 1
print(count)


def zip_sorted(a, b):
	return (zip(*sorted(zip(a, b)))[0], zip(*sorted(zip(a, b)))[1])

def gcd(a, b):
	return math.gcd(a, b)

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

def ncr(n, r):
	return math.comb(n, r)

def npr(n, r):
	return math.factorial(n) // math.factorial(n - r)

def decimal_to_binary(n):
	return bin(n).replace('0b', '')

def binary_to_decimal(s):
	return int(s, 2)
import sys, os.path
sys.setrecursionlimit(10 ** 5)
import math
from collections import defaultdict, deque
import heapq
input = sys.stdin.readline
I = lambda : list(map(int, input().split()))
S = lambda : list(map(str, input()))

def solve(cur, i, val):
	if i >= len(a):
		return val
	if (cur, i, val) in mem1:
		return mem1[cur, i, val]
	if cur + a[i] >= 0:
		mem1[cur, i, val] = max(solve(cur, i + 1, val), solve(cur + a[i], i + 1, val + 1))
		return mem1[cur, i, val]
	else:
		mem1[cur, i, val] = solve(cur, i + 1, val)
		return mem1[cur, i, val]
(n,) = I()
a = I()
l = []
heapq.heapify(l)
sum1 = 0
max1 = 0
for i in range(len(a)):
	heapq.heappush(l, a[i])
	sum1 += a[i]
	if sum1 < 0:
		while sum1 < 0:
			temp = heapq.heappop(l)
			sum1 -= temp
	max1 = max(max1, len(l))
print(max1)


import heapq

def get_max_potions(potions):
	taken_potions = []
	total = 0
	for p in potions:
		total += p
		heapq.heappush(taken_potions, p)
		while total < 0:
			total -= heapq.heappop(taken_potions)
	return len(taken_potions)
n = int(input())
potions = list(map(int, input().split()))
result = get_max_potions(potions)
print(result)


import heapq, math
from collections import defaultdict, deque
import sys, os.path
if os.path.exists('C:/Users/Dhanush/Desktop/cp/input.txt'):
	sys.stdout = open('C:/Users/Dhanush/Desktop/cp/output.txt', 'w')
	sys.stdin = open('C:/Users/Dhanush/Desktop/cp/input.txt', 'r')
input = sys.stdin.readline
n = int(input())
l = list(map(int, input().split()))
h = []
s = 0
count = 0
for i in l:
	s += i
	count += 1
	heapq.heappush(h, i)
	while s < 0:
		smallest = heapq.heappop(h)
		count -= 1
		s -= smallest
print(count)


import heapq
n = int(input())
a = list(map(int, input().split()))
h = []
heapq.heapify(h)
ans = 0
c = 0
for i in a:
	if i >= 0:
		c += i
		ans += 1
	elif c + i >= 0:
		c += i
		ans += 1
		heapq.heappush(h, i)
	elif h:
		if h[0] < i:
			c -= heapq.heappop(h)
			heapq.heappush(h, i)
			c += i
print(ans)


from heapq import heappop, heappush
n = int(input())
nums = list(map(int, input().split()))
l = []
count = 0
x = 0
for (i, val) in enumerate(nums):
	x += val
	count += 1
	if val < 0:
		heappush(l, val)
	while x < 0:
		p = heappop(l)
		x -= p
		count -= 1
print(count)


from heapq import heappush, heapify, heappop

def numberOfPotions(potion):
	heap = []
	heapify(heap)
	health = 0
	for i in potion:
		heappush(heap, i)
		health += i
		if health < 0:
			health -= heappop(heap)
	return len(heap)
n = int(input())
potion = list(map(int, input().split()))
print(numberOfPotions(potion))


import sys
import math
import collections
import heapq
input = sys.stdin.readline
n = int(input())
l = [int(i) for i in input().split()]
l1 = [0]
heapq.heapify(l1)
c = 0
s = 0
for i in range(n):
	if s + l[i] >= 0:
		c += 1
		s += l[i]
		heapq.heappush(l1, l[i])
	elif l1[0] < l[i]:
		s -= l1[0]
		s += l[i]
		heapq.heapreplace(l1, l[i])
print(c)


import heapq
from sys import stdin
input = stdin.readline
n = int(input())
arr = list(map(int, input().split()))
heap = []
cur = 0
for i in arr:
	heapq.heappush(heap, i)
	cur += i
	if cur < 0:
		cur -= heapq.heappop(heap)
print(len(heap))


import heapq
n = int(input())
arr = list(map(int, input().split()))
ans = 0
q = []
s = 0
for i in range(n):
	if s + arr[i] >= 0:
		ans += 1
		s += arr[i]
		if arr[i] < 0:
			heapq.heappush(q, arr[i])
	elif len(q) and q[0] < arr[i]:
		value = heapq.heappop(q)
		heapq.heappush(q, arr[i])
		s -= value
		s += arr[i]
print(ans)


import os
import sys
from io import BytesIO, IOBase
_print = print
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

	def __init__(self, file):
		self.buffer = FastIO(file)
		self.flush = self.buffer.flush
		self.writable = self.buffer.writable
		self.write = lambda s: self.buffer.write(s.encode('ascii'))
		self.read = lambda : self.buffer.read().decode('ascii')
		self.readline = lambda : self.buffer.readline().decode('ascii')

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

def mpint():
	return map(int, inp().split(' '))

def itg():
	return int(inp())
from heapq import *

def main():
	n = itg()
	ans = hp = 0
	heap = []
	for a in mpint():
		if a >= 0:
			ans += 1
			hp += a
			continue
		heappush(heap, a)
		hp += a
		if hp < 0:
			hp -= heappop(heap)
		else:
			ans += 1
	print(ans)
DEBUG = 0
URL = ''
if DEBUG == 1:
	import requests
	from ACgenerator.Y_Test_Case_Runner import TestCaseRunner
	runner = TestCaseRunner(main, URL)
	inp = runner.input_stream
	print = runner.output_stream
	runner.checking()
else:
	if DEBUG != 2:
		_print = lambda *args, **kwargs: ...
		(sys.stdin, sys.stdout) = (IOWrapper(sys.stdin), IOWrapper(sys.stdout))
	if DEBUG:

		def print(*args, **kwargs):
			_print(*args, **kwargs)
			sys.stdout.flush()
	main()


import heapq
n = int(input())
a = list(map(int, input().split()))
c = 0
s = 0
heap = []
for i in a:
	if i < 0:
		heapq.heappush(heap, i)
	s = s + i
	c += 1
	if s < 0:
		z = heapq.heappop(heap)
		s = s - z
		c -= 1
print(c)


import sys
from heapq import heappop, heappush

def get_fin():
	return open('input.txt', 'r') if '--local' in sys.argv else sys.stdin

def get_fout():
	return open('output.txt', 'w') if '--local' in sys.argv else sys.stdout

def solve():
	global fin, fout
	n = int(fin.readline())
	a = list(map(int, fin.readline().split()))
	result = 0
	heap = []
	for val in a:
		heappush(heap, val)
		result += val
		if result < 0:
			result -= heappop(heap)
	print(len(heap), file=fout)
with get_fin() as fin:
	with get_fout() as fout:
		solve()


import sys
import heapq
read = sys.stdin.readline

def run_case():
	n = int(read())
	ar = list(map(int, read().split()))
	heap = []
	i = 0
	s = 0
	res = 0
	while i < n:
		if ar[i] >= 0:
			s += ar[i]
			i += 1
			res += 1
		else:
			j = i
			while j < n and ar[j] < 0:
				j += 1
			tr = ar[i:j]
			i = j
			tr.sort(reverse=True)
			for t in tr:
				if s + t >= 0:
					s += t
					res += 1
					heapq.heappush(heap, t)
				elif len(heap) > 0 and heap[0] < t:
					s -= heap[0]
					res -= 1
					heapq.heappop(heap)
					s += t
					res += 1
					heapq.heappush(heap, t)
				else:
					break
	print(res)
run_case()


from heapq import heappushpop, heappush
n = int(input())
total = 0
ans = 0
potions = []
for i in map(int, input().split()):
	if total + i < 0:
		if len(potions):
			old_potion = heappushpop(potions, i)
			total -= old_potion
			total += i
	else:
		if i < 0:
			heappush(potions, i)
		total += i
		ans += 1
print(ans)


import sys
import math
from bisect import bisect_right as br
from bisect import bisect_left as bl
from heapq import heappush, heappop, heappushpop
from collections import defaultdict
from itertools import accumulate, chain
from collections import Counter
from collections import deque
from operator import itemgetter
from itertools import permutations
mod = 10 ** 9 + 7
inf = float('inf')

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

def LI():
	return list(map(int, sys.stdin.readline().split()))
n = I()
a = LI()
s = 0
ans = 0
h = []
for i in range(n):
	if s + a[i] >= 0:
		s += a[i]
		if a[i] < 0:
			heappush(h, a[i])
		ans += 1
	elif h:
		x = heappop(h)
		if x < a[i]:
			s += -x + a[i]
			heappush(h, a[i])
		else:
			heappush(h, x)
print(ans)


import heapq
n = int(input())
a = list(map(int, input().split()))
served = []
sum_ = 0
for i in range(n):
	heapq.heappush(served, a[i])
	sum_ += a[i]
	if sum_ < 0:
		sum_ -= heapq.heappop(served)
print(len(served))


import sys
import heapq
input = sys.stdin.readline
N = int(input())
A = list(map(int, input().rstrip().split(' ')))
B = [0]
heapq.heapify(B)
health = 0
for a in A:
	if health + a < 0:
		b = heapq.heappop(B)
		health -= b
		a = max(a, b)
	heapq.heappush(B, a)
	health += a
print(len(B) - 1)


import heapq, sys
input = sys.stdin.readline
(n, vals, drunk, curr) = (int(input()), [int(i) for i in input().split()], [], 0)
for i in vals:
	curr += i
	heapq.heappush(drunk, i)
	if curr < 0:
		curr -= heapq.heappop(drunk)
print(len(drunk))


import heapq as hq
n = int(input())
arr = list(map(int, input().split()))
minus = 0
minheap = []
dp = [0 for i in range(n)]
k = n
for i in range(n):
	if arr[i] >= 0:
		dp[i] = arr[i]
		k = i
		break
	else:
		minus += 1
for i in range(k, n):
	dp[i] = dp[i - 1] + arr[i]
	if arr[i] < 0:
		hq.heappush(minheap, arr[i])
	if dp[i] < 0:
		while dp[i] < 0:
			a = hq.heappop(minheap)
			minus += 1
			dp[i] -= a
print(n - minus)


from collections import Counter, defaultdict, deque
from heapq import *
import sys
input = sys.stdin.readline

def solve():
	n = int(input())
	a = [int(x) for x in input().split()]
	h = []
	hp = 0
	for el in a:
		hp += el
		if el < 0:
			heappush(h, el)
		while hp < 0:
			n -= 1
			hp -= heappop(h)
	print(n)
tt = 1
for test in range(tt):
	solve()


from heapq import heappush, heappop
import sys
input = sys.stdin.buffer.readline
n = int(input())
l = list(map(int, input().split()))
heap = []
count = 0
drunkval = 0
for i in l:
	if i > 0:
		count += 1
		drunkval += i
	elif drunkval + i < 0:
		if len(heap) > 0 and i > heap[0]:
			drunkval -= heappop(heap)
			drunkval += i
			heappush(heap, i)
	else:
		drunkval += i
		count += 1
		heappush(heap, i)
print(count)


from heapq import heapify, heappush, heappop
n = int(input())
arr = list(map(int, input().split()))
heap = []
heapify(heap)
_sum = 0
ans = 0
for i in range(n):
	_sum += arr[i]
	heappush(heap, arr[i])
	ans += 1
	while _sum < 0:
		pop = heappop(heap)
		_sum -= pop
		ans -= 1
print(ans)


n = int(input())
arr = list(map(int, input().split()))
heap = []
from heapq import heappop, heappush
cur = 0
for x in range(n):
	cur += arr[x]
	heappush(heap, arr[x])
	while cur < 0:
		k = heappop(heap)
		cur += -k
print(len(heap))


import heapq
n = int(input())
a = list(map(int, input().split()))
s = 0
h = []
for i in a:
	s += i
	heapq.heappush(h, i)
	if s < 0:
		s -= heapq.heappop(h)
print(len(h))


import heapq
n = int(input())
list1 = list(map(int, input().split()))
negitive = []
temp = 0
count = 0
ans = 0
for i in range(n):
	if temp + list1[i] >= 0:
		temp += list1[i]
		count += 1
		ans = max(ans, count)
		if list1[i] < 0:
			heapq.heappush(negitive, list1[i])
	elif negitive and -list1[i] < -negitive[0]:
		temp -= negitive[0]
		temp += list1[i]
		heapq.heapreplace(negitive, list1[i])
print(ans)


from collections import deque
import heapq
from math import sqrt
import operator
from operator import itemgetter
import sys
import copy
inf_var = 0
if inf_var == 1:
	inf = open('input.txt', 'r')
else:
	inf = sys.stdin
input = inf.readline

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

def read_one_float():
	return float(input().rstrip('\n'))

def read_list_of_ints():
	res = [int(val) for val in input().rstrip('\n').split()]
	return res

def read_list_of_ints_zero():
	return [int(val) - 1 for val in input().rstrip('\n').split()]

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

def main():
	n = read_one_int()
	elements = read_list_of_ints()
	cur_sum = 0
	res = 0
	q = []
	heapq.heapify(q)
	for el in elements:
		if cur_sum + el >= 0:
			res += 1
			cur_sum += el
			if el < 0:
				heapq.heappush(q, el)
		elif not q:
			continue
		elif el > q[0]:
			popped = heapq.heappop(q)
			cur_sum -= popped
			cur_sum += el
			heapq.heappush(q, el)
	print(res)
main()


from heapq import *
N = int(input())
pq = []
pos = 0
health = 0
for n in map(int, input().split()):
	if n >= 0:
		health += n
		pos += 1
	else:
		health += n
		heappush(pq, n)
		while health < 0:
			L = heappop(pq)
			health -= L
print(pos + len(pq))


import sys
import heapq

def solve(nums):
	sum = 0
	q = []
	removed = 0
	for num in nums:
		sum += num
		heapq.heappush(q, num)
		if sum < 0:
			sum -= heapq.heappop(q)
			removed += 1
	return len(nums) - removed

def main():
	stdin = sys.stdin
	stdin.readline()
	print(solve(list(map(int, stdin.readline().strip().split(' ')))))
main()


from sys import stdin, stdout

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

def INL():
	return [int(_) for _ in stdin.readline().split()]

def INS():
	return stdin.readline()

def MOD():
	return pow(10, 9) + 7

def OPS(ans):
	stdout.write(str(ans) + '\n')

def OPL(ans):
	[stdout.write(str(_) + ' ') for _ in ans]
	stdout.write('\n')
from heapq import heapify, heappush, heappop
n = INI()
X = INL()
x = 0
ans = 0
i = 0
h = []
heapify(h)
while i < n:
	if x < 0:
		ans -= 1
		u = heappop(h)
		x -= u
	else:
		x += X[i]
		ans += 1
		if X[i] < 0:
			heappush(h, X[i])
		i += 1
if x < 0:
	ans -= 1
OPS(ans)


from io import BytesIO, IOBase
from math import sqrt
import sys, os
from os import path
inpl = lambda : list(map(int, input().split()))
inpm = lambda : map(int, input().split())
inpi = lambda : int(input())
inp = lambda : input()
(rev, ra, l) = (reversed, range, len)
P = print
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))

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

def B(n):
	return bin(n).replace('0b', '')

def factors(n):
	arr = []
	for i in ra(2, int(sqrt(n)) + 1):
		if n % i == 0:
			arr.append(i)
			if i * i != n:
				arr.append(int(n / i))
	return arr

def prime_factors(n):
	omap = {2: 0}
	while n != 1 and n % 2 == 0:
		omap[2] += 1
		n /= 2
	for i in ra(3, int(math.sqrt(n)) + 1, 2):
		while n != 1 and n % i == 0:
			if i not in omap:
				omap[i] = 1
			else:
				omap[i] += 1
			n /= i
	if n != 1:
		omap[int(n)] = 1
	return omap

def dfs(arr, n):
	pairs = [[i + 1] for i in ra(n)]
	vis = [0] * (n + 1)
	for i in ra(l(arr)):
		pairs[arr[i][0] - 1].append(arr[i][1])
	pairs[arr[i][1] - 1].append(arr[i][0])
	comp = []
	for i in ra(n):
		stack = [pairs[i]]
		temp = []
		if vis[stack[-1][0]] == 0:
			while len(stack) > 0:
				if vis[stack[-1][0]] == 0:
					temp.append(stack[-1][0])
					vis[stack[-1][0]] = 1
					s = stack.pop()
					for j in s[1:]:
						if vis[j] == 0:
							stack.append(pairs[j - 1])
				else:
					stack.pop()
			comp.append(temp)
	return comp
from bisect import bisect_left as bl
from bisect import bisect_right as br
import sys, operator, math, operator
from collections import Counter
if path.exists('input.txt'):
	sys.stdin = open('input.txt', 'r')
	sys.stdout = open('output.txt', 'w')
import random, heapq
n = inpi()
li = inpl()
heap = []
heapq.heapify(heap)
su = 0
for i in ra(n):
	if su + li[i] < 0:
		if l(heap) > 0:
			ele = heapq.heappop(heap)
			if ele < li[i]:
				su -= ele
				su += li[i]
				heapq.heappush(heap, li[i])
			else:
				heapq.heappush(heap, ele)
	else:
		su += li[i]
		heapq.heappush(heap, li[i])
P(l(heap))


import heapq
n = int(input())
l = list(map(int, input().split()))
hp = []
heapq.heapify(hp)
cnt = 0
cur = 0
for i in range(n):
	if l[i] >= 0:
		cur += l[i]
		cnt += 1
	elif cur + l[i] >= 0:
		cur += l[i]
		heapq.heappush(hp, l[i])
	elif len(hp) > 0:
		x = heapq.heappop(hp)
		if x < l[i]:
			cur += -x
			cur += l[i]
			heapq.heappush(hp, l[i])
		else:
			heapq.heappush(hp, x)
print(cnt + len(hp))


import heapq
n = int(input())
arr = list(map(int, input().split()))
temp = []
total = 0
potions = 0
for i in arr:
	if i < 0:
		heapq.heappush(temp, i)
	total += i
	potions += 1
	while total < 0:
		total -= heapq.heappop(temp)
		potions -= 1
print(potions)


import heapq
n = int(input())
a = list(map(int, input().split()))
ans = 0
sum_ = 0
lst = []
heapq.heapify(lst)
for i in range(n):
	if a[i] >= 0:
		sum_ += a[i]
		ans += 1
	elif sum_ + a[i] >= 0:
		sum_ += a[i]
		heapq.heappush(lst, a[i])
		ans += 1
	elif len(lst) != 0:
		min_ = heapq.heappop(lst)
		if min_ > a[i]:
			heapq.heappush(lst, min_)
		else:
			heapq.heappush(lst, a[i])
			sum_ += a[i] - min_
print(ans)


import sys, os
import math
if os.path.exists('in.txt'):
	sys.stdin = open('in.txt', 'r')
from io import BytesIO, IOBase

def main():
	import heapq
	n = int(input())
	arr = list(MI())
	count = 0
	heap = []
	s = 0
	for i in arr:
		if i >= 0:
			s += i
			count += 1
		elif s + i >= 0:
			s += i
			heapq.heappush(heap, i)
			count += 1
		elif heap and heap[0] < i:
			s -= heapq.heappop(heap)
			heapq.heappush(heap, i)
			s += i
	print(count)
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

def outP(var):
	sys.stdout.write(str(var) + '\n')
MOD = 10 ** 9 + 7
mod = 998244353
main()


import heapq as h
n = int(input())
l = list(map(int, input().split()))
k = 0
a = 0
z = []
for i in l:
	if i < 0:
		h.heappush(z, i)
	if k + i >= 0:
		k += i
		a += 1
	else:
		k -= h.heappop(z)
		k += i
print(a)


from heapq import heapify, heappush, heappop
n = int(input())
l = [int(x) for x in input().split()]
temp = []
heapify(temp)
count = 0
s = 0
for i in l:
	if i < 0:
		heappush(temp, i)
	s += i
	count += 1
	if s < 0:
		count -= 1
		s -= heappop(temp)
print(count)


import sys
input = sys.stdin.readline
import heapq
n = int(input())
a = list(map(int, input().split()))
cnt = 0
hq = []
s = 0
for i in range(n):
	if a[i] >= 0:
		s += a[i]
		cnt += 1
	elif s + a[i] >= 0:
		heapq.heappush(hq, a[i])
		s += a[i]
		cnt += 1
	elif len(hq) == 0:
		continue
	else:
		x = heapq.heappop(hq)
		if x < a[i]:
			heapq.heappush(hq, a[i])
			s = s - x + a[i]
		else:
			heapq.heappush(hq, x)
print(cnt)


from sys import stdin, stdout
from math import ceil, floor, sqrt, log, log2, log10
from collections import Counter
import heapq
int_max = float('inf')
int_min = -float('inf')
input = stdin.readline

def solve():
	pass
t = 1
for _ in range(t):
	H = []
	n = int(input())
	for i in list(map(int, input().split())):
		tot = tot + i if 'tot' in locals() or 'tot' in globals() else i
		tot -= (heapq.heappush(H, i) if tot >= 0 else heapq.heappushpop(H, i)) or 0
	print(len(H))


import heapq
n = int(input())
a = [*map(int, input().split())]
(h, t) = ([], 0)
for i in a:
	t += i
	heapq.heappush(h, i)
	while t < 0:
		t -= heapq.heappop(h)
print(len(h))


import io
import os
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from heapq import heappush, heappop, heapify
from math import gcd, inf

class SortedList:

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

	def __len__(self):
		return self._len

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

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

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

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

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

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

def solve1(N, A):
	possible = {0: 0}
	for x in A:
		nextPossible = defaultdict(int)
		nextPossible.update(possible)
		for (numPot, life) in possible.items():
			if life + x >= 0:
				nextPossible[numPot + 1] = max(nextPossible[numPot + 1], life + x)
		possible = nextPossible
	return max(possible.keys())

def solve(N, A):
	negs = SortedList()
	negLife = 0
	pos = 0
	posLife = 0
	for x in A:
		if x >= 0:
			pos += 1
			posLife += x
		else:
			negs.add(x)
			negLife += x
			while posLife + negLife < 0:
				negLife -= negs.pop(0)
	return pos + len(negs)
DEBUG = False
if DEBUG:
	import random
	random.seed(0)
	for _ in range(100):
		N = random.randint(1, 10)
		A = [random.randint(1, 10) for i in range(N)]
		print('tc' + str(_), N, A)
		ans1 = solve1(N, A)
		ans = solve(N, A)
		assert ans == ans1
	exit()
input = io.BytesIO(os.read(0, os.fstat(0).st_size)).readline
TC = 1
for tc in range(1, TC + 1):
	(N,) = [int(x) for x in input().split()]
	A = [int(x) for x in input().split()]
	ans = solve(N, A)
	print(ans)


n = int(input())
a = list(map(int, input().split()))
import heapq
minl = []
heapq.heapify(minl)
minn = 1
summ = 0
count = 0
for i in a:
	summ += i
	if summ > -1:
		if i < 0:
			heapq.heappush(minl, i)
			minn = minl[0]
		count += 1
	elif i > minn:
		heapq.heappop(minl)
		heapq.heappush(minl, i)
		summ -= minn
		minn = minl[0]
	else:
		summ -= i
print(count)


import heapq
n = int(input())
a = list(map(int, input().split()))
pq = []
s = 0
for i in range(n):
	s += a[i]
	heapq.heappush(pq, a[i])
	while s < 0:
		s -= heapq.heappop(pq)
print(len(pq))


import heapq
n = int(input())
l = [int(x) for x in input().split()]
ans = 0
s = 0
h = []
heapq.heapify(h)
for i in l:
	s += i
	ans += 1
	if i < 0:
		heapq.heappush(h, i)
	while s < 0 and len(l):
		s -= heapq.heappop(h)
		ans -= 1
print(ans)


import os
import sys
from io import BytesIO, IOBase
BUFSIZE = 8192

class FastIO(IOBase):
	newlines = 0

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

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

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

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

class IOWrapper(IOBase):

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

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

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

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

def print_list(l):
	print(' '.join(map(str, l)))
from heapq import *
from collections import deque as dq
from math import ceil, floor, sqrt, pow, factorial, log2
from collections import Counter
n = N()
a = RLL()
cur = 0
ans = 0
h = []
heapify(h)
for i in range(n):
	cur += a[i]
	ans += 1
	heappush(h, a[i])
	while cur < 0:
		cur -= heappop(h)
		ans -= 1
print(ans)


import heapq
n = int(input())
drinkings = [int(item) for item in input().split(' ')]
health = 0
drinks = []
for i in range(n):
	health += drinkings[i]
	heapq.heappush(drinks, drinkings[i])
	if health < 0:
		Min = heapq.heappop(drinks)
		health -= Min
print(len(drinks))


import math
from collections import Counter
from itertools import permutations, combinations
import fractions
import heapq

def solve(test):
	n = int(input())
	a = [int(s) for s in input().split(' ')]
	H = []
	tot = 0
	for x in a:
		tot += x
		heapq.heappush(H, x)
		while tot < 0:
			tot -= H[0]
			heapq.heappop(H)
	print(len(H))
solve(1)


import os, sys, time, collections as c, math, pprint as p, itertools as it, operator as op, bisect as bs, functools as fn
(maxx, localsys, mod) = (float('inf'), 0, int(1000000000.0 + 7))
nCr = lambda n, r: reduce(mul, range(n - r + 1, n + 1), 1) // factorial(r)
ceil = lambda n, x: (n + x - 1) // x
(osi, oso) = ('/home/priyanshu/Documents/sublimetextproject/input.txt', '/home/priyanshu/Documents/sublimetextproject/output.txt')
if os.path.exists(osi):
	sys.stdin = open(osi, 'r')
	sys.stdout = open(oso, 'w')
input = sys.stdin.readline

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

def dprint(*args):
	[print(i) for i in args]
import heapq
n = int(input())
a = list(maps())
(tot, h) = (0, [])
heapq.heapify(h)
for i in a:
	tot += i
	heapq.heappush(h, i)
	while tot < 0:
		tot -= heapq.heappop(h)
print(len(h))


import heapq
n = int(input())
arr = list(map(int, input().split()))
health = 0
heap = []
for i in range(n):
	health += arr[i]
	heapq.heappush(heap, arr[i])
	if health < 0:
		health -= heapq.heappop(heap)
print(len(heap))