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.
Medium7Dynamic programmingGreedyIntervalsImplementationInterviewNo attempts yetTime limit2sMemory limit512 MBN 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 N. Block i has height Hi.
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.
Removing a block renumbers the remaining blocks. Suppose the heights from the left are (2,3,4,5,6) 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 (2,3,5,6) and the machine is in front of the block of height 3, which is block 2. Move right instead: the heights are the same (2,3,5,6) 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 A1,A2,…,AK of length K is non-decreasing when it satisfies A1≤A2≤⋯≤AK.
The first line contains the number of blocks N. (1≤N≤100000)
The second line contains the heights H1,H2,…,HN in order. (1≤Hi≤100000)
Print the minimum number of commands needed to reach the goal on the first line.
The first example is solved with the commands below. The block in front of the machine is shown in square brackets.
The second example needs these commands.