Lining Up in Order
Time limit1sMemory limit256 MB
Given a permutation of 1..N, find the fewest children to move to either end so the line becomes increasing; the answer is N minus the longest run of consecutive values that already appears in increasing order.
- Level
Medium6 of 10
- Topics
- Array, Dynamic programming, Greedy
- Solved
- No attempts yet
Problem
There are children standing in a single line in a playground. Each child wears a distinct number from to (that is, the numbers form a permutation of through ). A teacher wants to rearrange the children into increasing order of their numbers — — using only the following operation.
Operation: choose one child in the line and send that child to either the very front or the very back of the line.
When a child leaves a spot, the gap is closed: every child behind the gap steps forward by one position to fill it.
For example, suppose children stand in this order:
5 2 4 1 3
They can be sorted with three operations:
- Send child to the front. (
5 2 4 1 3→1 5 2 4 3) - Send child to the back. (
1 5 2 4 3→1 5 2 3 4) - Send child to the back. (
1 5 2 3 4→1 2 3 4 5)
No sequence of two or fewer operations can sort this arrangement, so the minimum number of moves here is .
Given the initial arrangement, find the minimum number of children that must be sent to the front or the back in order to line everyone up in increasing order of their numbers.
Input
The input consists of two lines. The first line contains an integer , the number of children. The second line contains the children's numbers in the order they are standing, separated by single spaces. It is guaranteed that and that the numbers form a permutation of the integers from to .
Output
Print, on a single line, the minimum number of children that must be sent to the front or the back to arrange them in increasing order of their numbers.