C - Leveling the Field Editorial /

Time Limit: 2 sec / Memory Limit: 1024 MiB

配点 : 333 点

問題文

高橋君は農家を営んでおり、横一列に並んだ N 区画の畑を持っています。各区画には土が積まれており、左から i 番目 (1 \leq i \leq N) の区画の土の高さは A_i です。

高橋君は作物を植える前に、すべての区画の土の高さを均一にしたいと考えています。そのために、以下の作業を好きな回数(0 回でもよい)行うことができます。

作業: 整数 l, r(1 \leq l \leq r \leq N)を選び、左から l 番目から r 番目までのすべての区画の土の高さをそれぞれ 1 だけ増やす。

作業ごとに選ぶ l, r は自由に決めることができ、以前と同じ値を再び選ぶこともできます。なお、土を取り除く作業はできないため、土の高さを減らすことはできません。

すべての区画の土の高さが同じになれば目標達成です。最終的な土の高さがいくらであっても構いません(ただし、土の高さを減らすことはできないため、最終的な高さは元の高さの最大値 \max(A_1, A_2, \ldots, A_N) 以上になります)。

高橋君が目標を達成するために必要な作業の最小回数を求めてください。

制約

  • 1 \leq N \leq 2 \times 10^5
  • 1 \leq A_i \leq 10^9
  • 入力はすべて整数

入力

N
A_1 A_2 \ldots A_N
  • 1 行目には、畑の区画数を表す整数 N が与えられる。
  • 2 行目には、各区画の土の高さを表す N 個の整数 A_1, A_2, \ldots, A_N がスペース区切りで与えられる。

出力

すべての区画の土の高さを同じにするために必要な作業の最小回数を 1 行で出力せよ。


入力例 1

5
3 1 4 1 5

出力例 1

7

入力例 2

8
2 5 3 7 4 7 1 6

出力例 2

16

入力例 3

12
100 85 90 70 95 60 80 75 88 92 65 100

出力例 3

102

Score : 333 pts

Problem Statement

Takahashi is a farmer who owns N plots of land arranged in a horizontal row. Each plot has soil piled on it, and the height of soil in the i-th plot from the left (1 \leq i \leq N) is A_i.

Before planting crops, Takahashi wants to make the soil height of all plots uniform. To achieve this, he can perform the following operation any number of times (possibly 0 times).

Operation: Choose integers l, r (1 \leq l \leq r \leq N), and increase the soil height of every plot from the l-th to the r-th from the left by 1.

For each operation, l and r can be chosen freely, and the same values as before may be chosen again. Note that there is no operation to remove soil, so the soil height cannot be decreased.

The goal is achieved when all plots have the same soil height. The final soil height can be any value (however, since soil height cannot be decreased, the final height must be at least \max(A_1, A_2, \ldots, A_N)).

Find the minimum number of operations Takahashi needs to achieve his goal.

Constraints

  • 1 \leq N \leq 2 \times 10^5
  • 1 \leq A_i \leq 10^9
  • All input values are integers

Input

N
A_1 A_2 \ldots A_N
  • The first line contains an integer N representing the number of plots.
  • The second line contains N integers A_1, A_2, \ldots, A_N separated by spaces, representing the soil height of each plot.

Output

Print in one line the minimum number of operations required to make the soil height of all plots the same.


Sample Input 1

5
3 1 4 1 5

Sample Output 1

7

Sample Input 2

8
2 5 3 7 4 7 1 6

Sample Output 2

16

Sample Input 3

12
100 85 90 70 95 60 80 75 88 92 65 100

Sample Output 3

102