您的位置:首页 > 其它

D - Buy Low Sell High(multiset)

2017-12-11 20:09 531 查看
You can perfectly predict the price of a certain stock for the next N days. You would like to profit on this knowledge, but only want to transact one share of stock per day. That is, each day you will either buy one share, sell one share, or do nothing. Initially you own zero shares, and you cannot sell shares when you don’t own any. At the end of the N days you would like to again own zero shares, but want to have as much money as possible.

Input

Input begins with an integer N (2 ≤ N ≤ 3·105), the number of days.

Following this is a line with exactly N integers p1, p2, …, pN (1 ≤ pi ≤ 106). The price of one share of stock on the i-th day is given by pi.

Output

Print the maximum amount of money you can end up with at the end of N days.

Example

Input

9
10 5 4 7 9 12 6 2 10

Output

20

Input

20
3 1 4 1 5 9 2 6 5 3 5 8 9 7 9 3 2 3 8 4

Output

41


Note

In the first example, buy a share at 5, buy another at 4, sell one at 9 and another at 12. Then buy at 2 and sell at 10. The total profit is  - 5 - 4 + 9 + 12 - 2 + 10 = 20.


C++ multiset ,学习使用堆……

#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
scanf("%d", &n);
multiset<int> s;//建立小顶堆
long long int ans = 0;
for(int i=0;i<n;i++)
{
int x;
scanf("%d", &x);
if(!s.empty()&&x>*s.begin())
{
ans += x - *s.begin();
s.erase(s.begin());//删除堆顶元素
s.insert(x);//插入一个元素
s.insert(x);
}
else
s.insert(x);
}
printf("%lld\n", ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: