We have n cards with each card numbered from 1 to n.
All cards are randomly shuffled.
We are only allowed the MoveCard (n) operation, which moves the card with the value n to the top of the pile.
We need to sort a bunch of cards with a minimum number of MoveCard operations.
The naive approach I can think of starts with MoveCard (n), MoveCard (n-1), MoveCard (n-2) ... MoveCard (1).
This approach will solve the problem in n MoveCard operations.
But we can optimize it.
For example, if the input is similar: 3 1 4 2
According to my approach:
4 3 1 2
3 4 1 2
2 3 4 1
1 2 3 4
MoveCard operations are 4.
But we can solve this problem with a minimum number of moves:
Optimized solution:
3 1 4 2
2 3 1 4
1 2 3 4
MoveCard operations are 2.
, , .
, , .
:
3 1 4 2
2 2 3 1 4 {2,3 4 }
1, . 1 2 3 4.