Editorial
Let be the minimum cost for the first castles when the last height is . Then
Separate heights by parity and write . For each parity, is a discrete convex function. Taking the minimum of the two neighboring previous states becomes a length-one sliding minimum of a convex function, which is supported by shifting the two lazy offsets in slope trick.
The adjustment cost is convex as well. If is even, add two asymmetric V-functions at the same vertex. If it is odd, add one at each of two neighboring vertices. This reproduces the exact cost on . Enforce positive heights using a lower-bound penalty whose weight is larger than the sum of all genuine cost slopes.
A weighted two-heap slope-trick structure processes every breakpoint in logarithmic time. The total complexity is . Use 128-bit integers for costs.