#K12161. Minimum Operations to Sort the Deck

    ID: 23630 Type: Default 1000ms 256MiB

Minimum Operations to Sort the Deck

Minimum Operations to Sort the Deck

You are given a deck of n cards, each uniquely labeled with an integer from 1 to n. The deck is arranged in an arbitrary order. Your task is to reorder the deck in increasing order (i.e. from 1 to n) using the minimum number of operations.

In one operation, you can take a card from anywhere in the deck and insert it at any position. The key observation to solve this problem is to identify the longest sequence of consecutive cards that are already in the correct increasing order. These cards do not need to be moved. Hence, the minimum number of operations required is given by

Operations=nL,\text{Operations} = n - L,

where L is the length of the longest consecutive increasing sequence (i.e. if a card labeled i appears after a card labeled i-1 in the deck, they are part of the consecutive sequence).

For example, consider the deck [3, 1, 2, 5, 4] with n = 5. The longest consecutive increasing sequence is [1, 2] (of length 2), so the answer is 5 - 2 = 3 operations.

inputFormat

The input is given via standard input (stdin) and has the following format:

  • The first line contains a single integer n representing the number of cards.
  • The second line contains n space-separated integers which denote the current order of the deck.

outputFormat

Output a single integer via standard output (stdout) which is the minimum number of operations needed to sort the deck in increasing order.

## sample
5
5 4 3 2 1
4

</p>