FunctionRacerProblemsRace

Raise Posts to Keep a Gap

EasyGreedyPython, JavaScript, TypeScript, Java, C++

heights[i] is the height of fence post i. In one move you raise a single post by 1; posts are never lowered. You want every post from the second one on to be at least gap higher than the post just before it. Return the fewest moves needed. A list with one post needs 0 moves.

Example 1

heights [1,1,1]
gap 1
returns 3

Raise the second post to 2 (1 move) and then the third to 3 (2 moves): 3 moves in all.

Example 2

heights [5,3,8,8]
gap 2
returns 8

Post 1 must reach 5 + 2 = 7 (4 moves), post 2 then needs 9 (1 move) and post 3 needs 11 (3 moves): 8 moves.

Constraints

Race itor take your time

Write it in your browser, against the clock. The model solution, stepped through line by line, comes after.

More Greedy problems