Roof
InterviewTime limit1.5sMemory limit128 MB
Given N column heights, pick a peak position and height so the roof shape h_j = peak - |peakpos - j| is positive everywhere, minimizing total absolute changes.
- Level
Medium6 of 10
- Topics
- Array, Prefix sum, Math, Implementation
- Solved
- No attempts yet
Problem
A histogram consists of columns whose heights are . You want to turn the histogram into a roof by performing operations. A roof is a histogram with the following properties.
- One column is the top of the roof. Let its position be .
- The column at position () has height .
- Every height is a positive integer.
One operation increases or decreases the height of a single column by . Find the minimum number of operations needed to turn the given histogram into a roof.
Input
The first line contains the number of columns in the histogram, ().
The second line contains numbers (), the initial column heights, separated by spaces.
Output
Print the minimum number of operations.
Hint
In the first example, raising the second, third, and fourth columns by each creates a roof whose top is the fourth column.
In the second example, lowering the third column by and raising the fourth column by turns the histogram into a roof. The picture below shows the second example.
