E.Buy Low Sell High
Problem Statement
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
Example 1
input
9
10 5 4 7 9 12 6 2 10
output
20
Example 2
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天的股票的价格,每天买入和卖出的价格是一样的,而且一天只能进行一次操作或者不进行操作。问你n天后最多能赚到多少钱。
思路
我们只要拿优先队列进行乱搞就行了
Code
#include<bits/stdc++.h>
using namespace std;
struct cmp {
bool operator ()(int a,int b) {
return a>b;
}
};
priority_queue<int,vector<int>,cmp>q;
int main() {
int n,x;
long long ans=0;
scanf("%d",&n);
for(int i=1;i<=n;++i) {
scanf("%d",&x);
if(!q.empty()&&q.top()<x) {
ans+=x-q.top();
q.pop();
q.push(x);
}
q.push(x);
}
printf("%lld\n",ans);
return 0;
}