Developer
Developer
Developer
BOI 2025, Day 2. Available memory: 512 MB. 2025.04.27
You are in charge of developing new properties in the suburbs of Toruń. You have already decided that there
will be one main street and n properties numbered from 1 to n along the street. The area is somewhat hilly,
and the elevation of the i-th property is ai centimetres.
It turns out that no one wants to buy a property that is on a slope. Formally, for elevations a1 , a2 , . . . , an ,
a slope is a contiguous subsequence ai−1 , ai , . . . , aj , aj+1 with 2 ≤ i ≤ j ≤ n − 1 such that either (i) ai−1 <
ai = ai+1 = . . . = aj < aj+1 , or (ii) ai−1 > ai = ai+1 = . . . = aj > aj+1 . Intuitively, a slope is a contiguous
range of properties at positions i − 1, i, i + 1, . . . , j, j + 1, where the elevations of all properties at positions
i, i + 1, . . . , j are equal to some h, and h is strictly between ai−1 and aj+1 .
You are able to increase or decrease the elevation of any property by any integer, but of course you
want to minimise the overall effort. Your task is to determine the minimal total change in elevation such
that there are no slopes at all. That is, you want to find elevations b1 , b2 , . . . , bn without slopes such that
|a1 − b1 | + |a2 − b2 | + . . . + |an − bn | is as small as possible. The elevations bi must be integers (in particular,
they don’t have to be positive), and there are no other constraints on bi .
Input
The first line contains an integer n (1 ≤ n ≤ 2 · 105 ) denoting the number of properties along the street.
The second line contains n integers a1 , a2 , . . . , an (0 ≤ ai ≤ 109 ), where the i-th integer ai is the initial
elevation of the i-th property.
Output
You should output the minimal total change in elevation to ensure that there are no slopes.
Example
For the input data: the correct result is:
11 5
7 2 1 2 5 7 8 8 10 8 8
This is illustrated below. The dashed lines represent the changed elevations without slopes bi of their corre-
sponding properties.
Elevation (ai )
10
9
8
7
6
5
4
3
2
1
Properties (i)
1 2 3 4 5 6 7 8 9 10 11
1/2 Developer
Scoring
Subtask Constraints Points
1 n ≤ 5 and ai ≤ 10 4
2 n ≤ 2000 13
3 ai ≤ 10 8
4 ai < ai+1 19
5 n ≤ 2 · 104 29
6 No additional constraints. 27