1762. Smooth the Ramp
A trail builder is planning a ramp made of n marker posts in a row. The current height of the post at position i is heights[i]. To make the ramp climb steadily, every post must end up strictly higher than the post before it. Raising or lowering a post by one unit costs one unit of effort, so changing post i to a new height new[i] costs |heights[i] - new[i]|. New heights may be any integers, including negative ones, and posts may be left unchanged.
Return the minimum total effort needed so that new[0] < new[1] < ... < new[n-1]. The total can exceed 32 bits, so return a long. The intended solution uses a heap and runs in O(n log n) time with O(n) space.
Example 1
- Input:
- heights = [3,2,1]
- Output:
- 4
- Explanation:
One optimal result is [1, 2, 3] (costs 2 + 0 + 2 = 4); no smaller total makes the heights strictly increasing.
Example 2
- Input:
- heights = [1,2,3,4]
- Output:
- 0
- Explanation:
The heights already increase strictly, so no changes are needed.
Example 3
- Input:
- heights = [5,5,5]
- Output:
- 2
- Explanation:
Change the heights to [4, 5, 6] at a cost of 1 + 0 + 1 = 2.
Constraints
1 ≤ n ≤ 105, where n = heights.length
-109 ≤ heights[i] ≤ 109
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms
Expected complexity
- Time
- O(n log n)
- Space
- O(n)