Sorting the Bookshelf

Interview

Time limit2sMemory limit128 MB

Summary
Find the minimum number of single-book relocations needed to sort a permutation of N books into increasing order.
Level

Medium5 of 10

Topics
Dynamic programming, Array, Greedy
Solved
No attempts yet

Problem

Donghyeok has come home from camp and is tidying his bookshelf. The books stand in a single long row, and each book is labeled with a number from 1 to N. Right now the books are all mixed up, and Donghyeok wants to rearrange them so that, read from left to right, they are in the order 1, 2, ..., N.

There is only one way to move a book: pull a single book out and reinsert it at any other position. The relative order of the remaining books stays the same.

For example, suppose the books are arranged like this:

1 5 2 3 4

If he pulls out book 5 and reinserts it at the very end, the row becomes

1 2 3 4 5

which is sorted from 1 to N, so the tidying is finished.

Given the current order of the books, find the minimum number of moves needed to finish sorting them.

Input

The first line contains the number of books N (1 ≤ N ≤ 200,000).

The second line contains the current order of the books, separated by spaces. This order is a permutation in which each number from 1 to N appears exactly once.

Output

Print, on the first line, the minimum number of moves Donghyeok must make to finish sorting the books.

Examples1

  1. Example 1

    Input
    5
    2 1 4 5 3
    
    Expected output
    2