PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#GD0000104. Mua thấp bán cao (Buy Low Sell High)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Mua thấp bán cao (Buy Low Sell High)

Buy Low Sell High

Source: Codeforces

Version: Phuoc Hung OJ Extended

Problem Statement

You know the stock price pip_i for each of nn days. On each day, you may buy one share, sell one owned share, or do nothing (at most one transaction per day). You start and end with zero shares, and cannot sell an unowned share. Find the maximum achievable profit.

Input

Line 1 contains nn. Line 2 contains nn prices pip_i.

Output

Print the maximum profit, which may be zero.

Subtasks

  • Subtask 1 (20 points): 2≤n≤122\le n\le 12; 1≤pi≤1061\le p_i\le10^6 for every ii.
  • Subtask 2 (30 points): 2≤n≤30002\le n\le 3000; 1≤pi≤1061\le p_i\le10^6 for every ii.
  • Subtask 3 (50 points): 2≤n≤3000002\le n\le 300000; 1≤pi≤1061\le p_i\le10^6 for every ii.

Examples

Input

3
1 2 3

Output

2

Explanation

Buy on day 11 for 11 and sell on day 33 for 33, earning 22. This is optimal with at most one action per day.