Climbers

Time limit: 0.55s Memory limit: 512MB Input: Output:

Task

A mountain range can be represented as a broken line that starts and ends at sea level (altitude 00) and has strictly positive altitudes in between (these are called inner altitudes). Alice and Bob start climbing the mountain range from both ends. They can move along the mountain range, back and forth, but they must stay at the same altitude (between them).

The effort of a path taken by Alice is the sum of absolute differences in altitudes on the path. Specifically, if Alice’s path begins at altitude h1=0h_1 = 0, changes directions at altitudes h2,h3,,hP1h_2, h_3, \dots, h_{P-1} and ends at altitude hPh_P, then the effort of that path is h2h1+h3h2++hPhP1|h_2−h_1|+|h_3−h_2|+\dots+|h_P−h_{P−1}|. (It follows that Bob will make an equal effort during this time).

Find the smallest effort Alice and Bob need to make in order to meet.

Input data

The mountain range is encoded as an array of NN integers containing the altitudes of the segment endpoints. The first line contains NN. The second line contains the NN integers. The first and last integers are guaranteed to be 00.

Output data

Print a single integer, the minimum effort required for Alice and Bob to meet. If there is no way for them to meet, print the word NO instead.

Constraints and clarifications

  • 3N5 0003 \leq N \leq 5 \ 000
  • Inner altitudes are between 11 and 1 000 0001 \ 000 \ 000.
  • Test cases will be scored individually.
# Points Constraints
1 25 All inner altitudes are distinct.
2 30 NH45 000N \cdot H ≤ 45 \ 000, where HH is the highest altitude.
3 50 No additional constraints.

Example 1

stdin

5
0 4 2 7 0

stdin

11

Explanation

Alice and Bob move towards one another to altitude 44.

Then they both move right and descend to altitude 22.

Finally, they move towards one another and meet at altitude 77.

Example 2

stdin

7
0 10 1 20 5 10 0

stdin

48

Log in or sign up to be able to send submissions!