E. Buy Low Sell High(贪心+set)

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

题目大意:。。。。。。

题目思路:

对于这题,一开始我想的贪心思路是 从大到小去考虑,对于每一个最大的从第一个位置到这个当前最大的数的位置中找到一个最小的,用线段树维护,我觉得我想的非常对啊,但是wa了,后面发现我这样的做法有一个问题,我这样的做法,对于有一些来说是只有卖出操作,没有买入操作的。。后面看了题解,,,

其实我们可以发现我们价值的收益是有传递性的,也就是说如果a<b<c,我们先算出b-a,在算出c-b,相当于就是c-a的最大收益,那么这样的话我们就可以用一个multiset维护

如果当前值比集合里最小的大那我们,就可以获得收益,在插两个当前值进去,这样子做是因为我们需要让其有传递性,而且在当前位置我也可以买入,所以有两个

ac代码:

#include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<sstream>
#include<map>
#include<vector>
#include<set>
#define LL long long
#define INF 0x3f3f3f3f
#define LLINF 0x3f3f3f3f3f3f3f
#define lson rt<<1
#define rson rt<<1|1
using namespace std;
int n;
int main()
{
    multiset<int>Q;
    scanf("%d",&n);
    LL ans = 0;
    for(int i = 0;i<n;i++){
        int x;
        scanf("%d",&x);
        if(Q.size()==0||(*Q.begin())>x){
                Q.insert(x);
        }
        else{
            ans += x-*Q.begin();
            Q.erase(Q.begin());
            Q.insert(x);
            Q.insert(x);
        }
    }
    cout<<ans<<endl;
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值