C2. Potions (Hard Version)

time limit per test

1 second

memory limit per test

256 megabytes

This is the hard version of the problem. The only difference is that in this version n≤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 increases your health by ai when drunk. ai can be negative, meaning that the potion decreases your health.

You start with 0 health, and you will walk from left to right, from the 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≤n≤200000) --- the number of potions.

The next line contains n integers a1, a2, ... ,an (−109≤ai≤109) 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.

Example

Input

Copy

复制代码

6

4 -4 1 -3 1 -3

Output

Copy

复制代码
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

解题说明:此题是一道模拟题,可以采用贪心算法,从左到右遍历,先全部喝掉。如果血量变负,就丢掉之前喝过的负收益最大的那瓶(因为丢掉它能让血量增加最多)。这里需要用到小根堆,用来维护的是已喝的负值药水,堆顶就是最该丢掉的那个。

cpp 复制代码
#include<bits/stdc++.h>
#include<algorithm>
#include<vector>
#include<iostream>
using namespace std;
typedef long long ll;
priority_queue<int, vector<int>, greater<int> >pq;
int main() 
{
	ll n, s = 0, c = 0;
	cin >> n;
	while (n--)
	{
		int x;
		cin >> x;
		pq.push(x); 
		c += x;
		s++;
		if (c < 0)
		{ 
			c -= pq.top();
			pq.pop(); 
			s--; 
		}
	}
	cout << s<<endl;
	return 0;
}
相关推荐
cpp_learner8 分钟前
C++ 实现责任链模式(Chain of Responsibility):从一堆 if-else 到可插拔的处理管道
c++·设计模式
一木 之林23 分钟前
五、C++ 新特性、关键字与编译原理(进阶)(一)
c语言·开发语言·c++
2601_9622982724 分钟前
交易开拓者通常使用什么编程语言?这种语言如何帮助自动化交易?
java·c++·python·编程语言·自动化交易
码匠许师傅30 分钟前
【设计模式精讲】23.备忘录模式(Memento)
c++·设计模式·软件工程·uml·备忘录模式
键盘会跳舞1 小时前
【C++多线程】thread_local 深度剖析:线程局部存储的生命周期与实现
c++·多线程·thread_local
whitelbwwww1 小时前
c++ 多线程
开发语言·c++·算法
努力努力再努力wz1 小时前
【Docker入门系列】:从架构演进到容器化:一文建立 Docker、虚拟化与 Namespace 的底层心智模型
运维·开发语言·数据结构·c++·docker·容器·架构
光电笑映1 小时前
Linux 线程编程:从进程、分页到线程控制与封装
linux·运维·服务器·c++
qinzechen1 小时前
本周科技行业热点汇总·2026第36周(2026年8月31日-9月6日)
c++·科技·算法
aqiu1111112 小时前
【C++ 代码分析与重构】常见 DFS 逻辑错误解析与修正
c++·重构·深度优先