Problem Statement | |||||||||||||
Bridge is a card game in which you are dealt a collection of cards, called a hand. You pick up your hand and hold it so that you can see the fronts of your cards but other players can only see the backs. You are free to arrange the cards in any order, but deciding on a good arrangement is not always straightforward. You could sort them, but that might give your opponents too many clues. For example, if you pull out the leftmost card, they might be able to guess that the card is either your lowest or your highest in that suit. You could leave the hand completely unsorted, but most people find it too difficult to keep track of their cards that way. A good compromise between security and ease of use is to group the cards by suit, arrange the suits in alternating colors, and leave the cards within each suit unsorted. More precisely, an arrangement of cards is deemed valid if and only if
2C KC 4C 5H 3H 2H AH QS KS 6D TD 9D JDis valid, but none of the following hands are valid: 2C KC 5H 4C 3H 2H AH QS KS 6D TD 9D JD (a heart is between two clubs) 2C KC 4C 5H 3H 2H AH 6D TD 9D JD QS KS (hearts and diamonds are adjacent) 2C KC 4C 5H 3H 2H AH QS KS 6D 9D TD JD (diamonds are sorted in increasing order) 2C KC 4C AH 5H 3H 2H QS KS 6D TD 9D JD (hearts are sorted in decreasing order)Notice that, in all of these examples, the spades are allowed to be in increasing order because there are only two of them. Also, notice that aces are considered high, so "5H 3H 2H AH" is not in decreasing order, but "AH 5H 3H 2H" is. When arranging your hand, you move cards one at a time by pulling them out of their current positions and reinserting them at other positions. Given a hand, you are to calculate and return the minimum number of moves necessary to achieve a valid arrangement. The hand will be represented by a String[] cards. Each element of cards represents a separate card as a two-character string of the form <rank><suit>. The possible ranks, listed in increasing order, are {'2'-'9','T','J','Q','K','A'}. The possible suits are {'C','D','H','S'}. For example, the jack of hearts would be written "JH". | |||||||||||||
Definition | |||||||||||||
| |||||||||||||
Notes | |||||||||||||
- | In real bridge, a hand always starts with 13 cards, but in this problem, a hand might be bigger or smaller than that. | ||||||||||||
Constraints | |||||||||||||
- | cards contains between 3 and 50 elements, inclusive. | ||||||||||||
- | Each element of cards contains exactly two characters, in the format described above. | ||||||||||||
- | cards contains no duplicate elements. | ||||||||||||
Examples | |||||||||||||
0) | |||||||||||||
| |||||||||||||
1) | |||||||||||||
| |||||||||||||
2) | |||||||||||||
| |||||||||||||
3) | |||||||||||||
| |||||||||||||
4) | |||||||||||||
|