using
System;
using
System.Collections.Generic;
class
Program
{
static
int
Solve(List<
int
> arr)
{
long
currentSum = 0;
int
elementsAdded = 0;
PriorityQueue<
int
> negativeElements =
new
PriorityQueue<
int
>();
for
(
int
i = 0; i < arr.Count; i++)
{
int
currentElement = arr[i];
currentSum += currentElement;
elementsAdded++;
negativeElements.Push(-currentElement);
while
(currentSum < 0)
{
elementsAdded--;
currentSum += negativeElements.Pop();
}
}
return
elementsAdded;
}
static
void
Main()
{
List<
int
> arr =
new
List<
int
> { 4, -4, 1, -3, 1, -3 };
int
result = Solve(arr);
Console.WriteLine(result);
}
}
class
PriorityQueue<T>
where
T : IComparable<T>
{
private
List<T> heap;
public
PriorityQueue()
{
heap =
new
List<T>();
}
public
int
Count
{
get
{
return
heap.Count; }
}
public
void
Push(T value)
{
heap.Add(value);
int
currentIndex = heap.Count - 1;
while
(currentIndex > 0)
{
int
parentIndex = (currentIndex - 1) / 2;
if
(heap[currentIndex].CompareTo(heap[parentIndex]) > 0)
{
Swap(currentIndex, parentIndex);
currentIndex = parentIndex;
}
else
{
break
;
}
}
}
public
T Pop()
{
if
(heap.Count == 0)
{
throw
new
InvalidOperationException(
"Priority queue is empty"
);
}
T root = heap[0];
heap[0] = heap[heap.Count - 1];
heap.RemoveAt(heap.Count - 1);
int
currentIndex = 0;
while
(
true
)
{
int
leftChildIndex = 2 * currentIndex + 1;
int
rightChildIndex = 2 * currentIndex + 2;
if
(leftChildIndex >= heap.Count)
{
break
;
}
int
childIndex = leftChildIndex;
if
(rightChildIndex < heap.Count &&
heap[rightChildIndex].CompareTo(heap[leftChildIndex]) > 0)
{
childIndex = rightChildIndex;
}
if
(heap[currentIndex].CompareTo(heap[childIndex]) < 0)
{
Swap(currentIndex, childIndex);
currentIndex = childIndex;
}
else
{
break
;
}
}
return
root;
}
private
void
Swap(
int
index1,
int
index2)
{
T temp = heap[index1];
heap[index1] = heap[index2];
heap[index2] = temp;
}
}