Block Game
InterviewTime limit2sMemory limit512 MB
Remove every block so the heights leave in non-decreasing order, minimizing moves of a machine that walks left and right along the shrinking row.
- Level
Medium7 of 10
- Topics
- Dynamic programming, Greedy, Intervals, Implementation
- Solved
- No attempts yet
Problem
blocks stand in a row. The leftmost block is block 1, the block to its right is block 2, and in the same way the rightmost block is block . Block has height .
One small machine sits in front of the row. At the start it is in front of block 1. The goal is to remove all of the blocks with that machine. The heights written down in removal order must form a non-decreasing sequence.
The machine takes three commands.
- Move to the block on the right. If the machine was in front of block , it goes in front of block . You cannot give this command when there is no block on the right.
- Move to the block on the left. If the machine was in front of block , it goes in front of block . You cannot give this command when there is no block on the left.
- Remove the block in front of the machine and move to the block on the left or on the right. You fix the direction when you give the command. If no block is left on either side after the removal, the machine does not have to move.
Removing a block renumbers the remaining blocks. Suppose the heights from the left are and the machine is in front of the block of height 4. That block is third from the left, so it is block 3. Remove it and move left: the heights become and the machine is in front of the block of height 3, which is block 2. Move right instead: the heights are the same and the machine is in front of the block of height 5, which is block 3.
Write a program that computes the minimum number of commands needed to reach the goal.
A sequence of length is non-decreasing when it satisfies .
Input
The first line contains the number of blocks . ()
The second line contains the heights in order. ()
Output
Print the minimum number of commands needed to reach the goal on the first line.
Hint
The first example is solved with the commands below. The block in front of the machine is shown in square brackets.
- Start: [1] 2 3
- Remove and move right: [2] 3
- Remove and move right: [3]
- Remove
The second example needs these commands.
- Start: [4] 2 1 3
- Move right: 4 [2] 1 3
- Move right: 4 2 [1] 3
- Remove and move left: 4 [2] 3
- Remove and move right: 4 [3]
- Remove and move left: [4]
- Remove