# Codeforces Round #437 (Div. 1)D Buy Low Sell High（贪心+优先队列/multiset）

## 2018 年 08 月 27 日 • 阅读: 1259 • 练习 • 阅读设置

• time limit per test: 2 seconds
• memory limit per test: 256 megabytes

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·10^5$), the number of days.

Following this is a line with exactly N integers $p_1, p_2, ..., p_N(1 ≤ p_i ≤ 10^6)$. The price of one share of stock on the i-th day is given by $p_i$.

### Output

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

### 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.

### 链接

http://codeforces.com/contest/866/problem/D

### 题解

• 写法一

• Accepted 140 ms 6200 KB
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <set>
#include <algorithm>
typedef long long ll;
using namespace std;

int main()
{
int n;
ll x, ans = 0;
priority_queue <ll, vector <ll>, greater <ll> > Q;
//    scanf("%d", &n);
cin >> n;
for (int i = 0; i < n; ++i)
{
scanf("%lld", &x);
Q.push(x);
if (Q.top() < x)
{
ans += x - Q.top();
Q.pop();
Q.push(x);
}
}
//    printf("%lld\n", ans);
cout << ans << endl;
return 0;
}
• 写法二

• Accepted 234 ms 9600 KB
#include <iostream>
#include <cstdio>
#include <cstring>
#include <queue>
#include <set>
#include <algorithm>
typedef long long ll;
using namespace std;

int main()
{
int n;
ll x, ans = 0;
multiset <ll> S;
cin >> n;
for (int i = 0; i < n; ++i)
{
scanf("%lld", &x);
S.insert(x);
if (*S.begin() < x)
{
ans += x - *S.begin();
S.erase(S.begin());
S.insert(x);
}
}
cout << ans << endl;
return 0;
}

The end.
2018-08-27 星期一