Block Game

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 MB

Problem

NN 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 NN. Block ii has height HiH_i.

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 ii, it goes in front of block i+1i+1. 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 ii, it goes in front of block i1i-1. 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 (2,3,4,5,6)(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)(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)(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,,AKA_1, A_2, \dots, A_K of length KK is non-decreasing when it satisfies A1A2AKA_1 \le A_2 \le \dots \le A_K.

Input

The first line contains the number of blocks NN. (1N1000001 \le N \le 100000)

The second line contains the heights H1,H2,,HNH_1, H_2, \dots, H_N in order. (1Hi1000001 \le H_i \le 100000)

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