Task
A mountain range can be represented as a broken line that starts and ends at sea level (altitude ) 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 , changes directions at altitudes and ends at altitude , then the effort of that path is . (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 integers containing the altitudes of the segment endpoints. The first line contains . The second line contains the integers. The first and last integers are guaranteed to be .
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
- Inner altitudes are between and .
- Test cases will be scored individually.
# | Points | Constraints |
---|---|---|
1 | 25 | All inner altitudes are distinct. |
2 | 30 | , where 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 .
Then they both move right and descend to altitude .
Finally, they move towards one another and meet at altitude .
Example 2
stdin
7
0 10 1 20 5 10 0
stdin
48