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;
}
相关推荐
科技苑6 小时前
C++ CAS与ABA问题详解,无锁编程的经典陷阱怎么解决?
c++·人工智能
BaiPeter11 小时前
ZPL文件预览
开发语言·c++
悠仁さん13 小时前
【C++】哈希表
c++·算法·散列表
Severus_black15 小时前
【C++初阶】list使用及相关实现,思路顺滑流畅!
c语言·数据结构·c++·stl·list
敲上瘾17 小时前
Qt Widgets入门:项目模板解析与Hello World
开发语言·数据库·c++·qt·ui·qt6.3
旖旎夜光18 小时前
【C++ 基础入门】C++ 多态(中):虚函数表、多态原理与动静绑定
开发语言·c++·笔记·学习
旖旎夜光19 小时前
【C++ 基础入门】C++多态(下):单/多继承虚表、多态补充与 21 道高频题
开发语言·c++·笔记·学习
apcipot_rain1 天前
C++转Java日记(03)
java·开发语言·c++
布莱克6051 天前
C++ 中 map 的 insert 与 emplace:key 已存在时会覆盖吗?
开发语言·数据结构·c++·算法·map
xys_6781 天前
深挖C++:类和对象(中)
开发语言·c++