Buy Low Sell High
time limit per test:2 seconds
memory limit per test:256 megabytes
input:standard input
output:standard output
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.
Examples
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.
对于每一个价格,我不管具体方案是什么,我只要能计算出最后的最优解即可。那么我们可以先强行在所有时刻买入,然后对应每个时刻在优先队列里面加入两个价值的相反数。对于每一个时刻,我选取一个队列中最大的负数相加。如果是负数恰好是这个数字的相反数,那么表示在这个时刻不操作(加减抵消),否则表示在对应负数价值的时候买入而在此时卖出,把差价记入贡献。可能你会说,我可能在当前时刻卖出并不是最优的解法。当时正如一开始所说的,我们不管具体方案是什么,这么做并不代表此刻卖出。举一个简单的例子,股票价1、2、3,那么ans=1-1+2-1+3-2。第二个时刻虽然加入了差价,但是很快第三个时刻又把3与2的差价加上去,如果加上括号ans=1-1+3+(2-2)-1,相当于这个第二个时刻没有进行任何操作。
#include<cstdio>
#include<queue>
#include<iostream>
using namespace std;
priority_queue<int>q;
int main() {
int n;
long long ans = 0;
scanf("%d", &n);
for (int i = 1; i <= n; i++) {
int u;
scanf("%d", &u);
q.push(-u);
q.push(-u);
int a_top = q.top();
ans += u + a_top;
q.pop();
}
printf("%I64d", ans);
return 0;
}