Buy Low Sell High CodeForces - 867E(贪心+优先队列)

Buy Low Sell High CodeForces - 867E

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.

题意:

有一个物品,在n天内有不同的价格,每天可以选择买入或者卖出该物品,而且只能操作一次,初始手上没有该物品,问能获得的最大利益是多少。

分析:

对于一个数字,如果之后的的数字如果比这个数字还大,那么我们可以当作之前买了一个,然后现在卖出去,可是这样的做法存在问题,比如1,2,3,66,按照那样的做法,我们的收益是2-1+66-3=64,然而66-1+3-2=66,很明显之前的做法存在错误,错误的核心在于对于买卖对象确认的错误
那么,如果我们把之前的数字a放入优先队列,在遇到b的时候拿出来,把现在的数字b放入有优先队列两次,而收益暂时放入ans中,假如说,后面有一个数字c用到了现在处于优先队列的队头b,如果我们用了这个b,实际上我们是用c买了之前的a,原因是这样的,从收益上看,收益是c-b+(b-a)=c-a,而从优先队列上看,队列里面都是只存在b,不存在a,这样的话,我们就是始终保持当前ans最大,并且当后面的选择与前面选择冲突的时候,让之前的选择充当一个跳板,使得我们的ans依旧是最优的

code:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
priority_queue<int,vector<int>,greater<int> >q;

int main(){
    int n,w;
    ll ans = 0;
    cin >> n;
    while(n--){
        scanf("%d",&w);
        if(!q.empty() && w > q.top()){
            ans += w - q.top();
            printf("%d\n",w-q.top());
            q.pop();
            q.push(w);
        }
        q.push(w);
    }
    cout << ans << endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/codeswarrior/article/details/82110978
今日推荐