Ctrl K

Terraces Going One Way

Hard
Plots run in a row along a hillside, and plot i has height heights[i]. In one step you can raise or lower any single plot by exactly 1. The row of heights must become monotonic: either non-decreasing (each plot is no lower than the one before it) or non-increasing (each plot is no higher). You choose the direction. Return the minimum number of steps.
Example 1
heights=[4, 1, 3, 2] → 2

Raise the second plot from 1 to 2 and lower the third from 3 to 2: the row becomes [4, 2, 2, 2], which never goes up. Two steps in total.

Example 2
heights=[2, 6, 3, 8] → 3

Lower 6 to 3: [2, 3, 3, 8] never goes down. That takes 3 steps, and no way is shorter.

Example 3
heights=[9, 9, 5, 0] → 0

The heights already never go up, so nothing needs to change.

Constraints
  • 1 ≤ len(heights) ≤ 1000
  • 0 ≤ heights[i] ≤ 1000
Have you seen this problem in a real interview?
Solved by0
Tried by0
Submissions0
Acceptance—
Topics
Similar problemsDoes the Text Fit the Pattern HardThe Heaviest Reading Day HardFuel Stops Along the Way HardMirror Chunk Split HardFewest Lawn Sprinklers Hard
loading Python…
Input
heights=[4, 1, 3, 2]
Expected
2

Run checks the first 3 tests in your browser. Submit checks all 138 tests on the server, hidden ones included.