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.

思路:依旧是贪心,维护一个优先队列,每次读取一个数与队顶判断,如果大于就出队并入队2次读取的数,答案加上差值,否则就入队一次。为什么要入队两次,因为有可能这次不应该卖,应该买,所以就需要入2次,例如:1 3 5 6,读取3时,答案加上2,这次应该是不卖而是买,入队2次,这样下次就是叠加上次的操作,5 - 3 + 3 - 1 == 5 - 1代码如下:

int n;

int main() {
scanf("%d", &n);
priority_queue<LL,vector<LL>,greater<LL>> q;
LL sum = , now;
scanf("%I64d", &now);
q.push(now);
for(int i = ; i < n; ++i) {
scanf("%I64d", &now);
if(now > q.top()) {
sum += now - q.top();
q.pop();
q.push(now);
}
q.push(now);
}
printf("%I64d\n",sum);
return ;
}

最新文章

  1. Redhat/Ubuntu/Windows下安装Docker
  2. MVC系列1-MVC基础 (ASP.NET)
  3. js-JavaScript高级程序设计学习笔记15
  4. IOS开发-图片尺寸
  5. POJ3784 Running Median
  6. BZOJ3682 : Phorni
  7. poj 1848 树形dp
  8. NOIP2013 货车运输 LCA倍增+最大生成树
  9. creating normals from alpha/heightmap inside a shader
  10. Android开发学习之TypedArray类
  11. Hiddenfield控件
  12. Wix打包系列(四) 自定义UI
  13. vue+vuex初入门
  14. ng-init小解
  15. java并发包下的并发工具类
  16. HALCON不支持的设备中,获取图像
  17. 神奇的namespace使用
  18. 12C数据库ORA-40365: The SYS user cannot be locked while the password file is in its current format
  19. django学习自修第一天【简介】
  20. ELF文件解析(二):ELF header详解

热门文章

  1. 模块学习-shutil
  2. Vue 使用MD5 加密
  3. 使用 OClint 进行静态代码分析
  4. Mysql 一些细节方面解析(一)--MyISAM和InnoDB的主要区别和应用场景
  5. Linux文件系统与日志!
  6. nyoj 40
  7. 深入JAVA注解-Annotation(学习过程)
  8. js面试必考:this
  9. JavaScript高级特征之面向对象笔记二
  10. git add 添加错文件 撤销