#K62152. Minimum Moves to Sort Books

    ID: 31468 Type: Default 1000ms 256MiB

Minimum Moves to Sort Books

Minimum Moves to Sort Books

You are given n, the number of books, and an array of n integers representing the weights of the books, in the current order. The goal is to calculate the minimum number of moves required to rearrange the books so that their order becomes non-decreasing.

A "move" consists of taking one book and placing it in the correct position. It turns out that if you can identify a longest subsequence of books that already form a consecutive sequence (in the sense that if a book has weight w then the previous book in the subsequence must have weight w-1), you only need to move the remaining books. In mathematical terms, if L is the length of the longest subsequence satisfying

$a_i = a_{i-1} + 1$

then the answer is

$n - L$

This problem is a twist on the classic longest increasing subsequence problem. However, here, only consecutive increments (i.e. difference of exactly 1 between adjacent elements in the subsequence) count toward the solution.

inputFormat

The input is read from stdin and consists of two lines:

  1. The first line contains a single integer n representing the number of books.
  2. The second line contains n space-separated integers representing the weights of the books.

outputFormat

Output a single integer to stdout, the minimum number of moves required such that the books are arranged in non-decreasing order.

## sample
5
3 1 2 5 4
3

</p>