CF-867-E-Buy Low Sell High(贪心,物品买卖)

题目链接:http://codeforces.com/problemset/problem/867/E

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.

题目大意:给你一个n天的股票售价,每天只能进行一种操作(买/卖/啥都不干),问你能够获得的最大收益是多少,(从左往右,时间无法倒流)

物品买卖的题,碰见一个股票,啥都不说,先预定(预定,但不买)下来(放入优先队列),如果它以后能升值,则刷新这个股票的价值,然后获利,如果不能升值,则最后的时候不计算它;

ac:

#include<stdio.h>
#include<string.h>  
#include<math.h>  
  
#include<map>   
//#include<set>
#include<deque>  
#include<queue>  
#include<stack>  
#include<bitset> 
#include<string>  
#include<fstream>
#include<iostream>  
#include<algorithm>  
using namespace std;  

#define ll long long  
#define INF 0x3f3f3f3f  
//#define mod 1e9+7
//#define max(a,b) (a)>(b)?(a):(b)
//#define min(a,b) (a)<(b)?(a):(b) 
#define clean(a,b) memset(a,b,sizeof(a))// 水印 
//std::ios::sync_with_stdio(false);

int n;
//priority_queue<> que;
struct cmp{
	bool operator ()(const ll &a,const ll &b){
		return a>b;
	}
};

int main()
{
	int n;
	scanf("%d",&n);
	priority_queue<ll,vector<ll>,cmp> que;
	while(que.size())
		que.pop();
	ll ans=0;
	for(int i=1;i<=n;++i)
	{
		ll x;
		scanf("%lld",&x);
		que.push(x);//先预定 
		if(que.top()<x)//如果能够升值 
		{
			ans=ans+x-que.top();//获利 
			que.pop(); 
			que.push(x);//将之前的那个股票升值 
		}
	}
	printf("%lld\n",ans);
}

猜你喜欢

转载自blog.csdn.net/qq_40482358/article/details/82180259
今日推荐