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;
}
相关推荐
Tyler_TXZ2 小时前
C++C语言之——树
c语言·c++·算法·
旖旎夜光2 小时前
LeetCode 30:串联所有单词的子串(滑动窗口) —— 题解
数据结构·c++·算法·leetcode·滑动窗口
星恒随风2 小时前
C++ 红黑树封装(二):迭代器、const_iterator 与 operator[] 完整实现 mymap 和 myset
开发语言·c++·状态模式
小小龙学IT2 小时前
oneTBB 开源并行编程库深度解析:从工作窃取调度器到 flow graph 实战
c++·开源
ShineWinsu3 小时前
对于C++:缓冲区管理的详细解析
linux·c++·面试·编程·笔试·io·缓冲区
h_a_o777oah4 小时前
【算法基础】卡特兰数:递推定义与折线对称公式推导及解题策略
c++·算法·acm·组合数学·卡特兰数·反射原理·动态规划dp
帅气的小峰4 小时前
pybind11与nanobind可以共存吗?如何迁移?
c++·python·cuda·推理引擎
syker4 小时前
SuperNova Compiler v4.2.9 完整开发手册
c++
zhy295634 小时前
在 QAIRT Genie SDK 上部署 Llama 3.2 1B 模型:从环境准备到 C++ 推理
开发语言·c++·llama