Input: ranks =[13,2,3,1,9], suits =["a","a","a","a","a"]Output: "Flush"Explanation: The hand with all the cards consists of 5 cards with the same suit, so we have a "Flush".
Input: ranks =[4,4,2,4,4], suits =["d","a","a","b","c"]Output: "Three of a Kind"Explanation: The hand with the first, second, and fourth card consists of 3 cards with the same rank, so we have a "Three of a Kind".Note that we could also make a "Pair" hand but "Three of a Kind"is a better hand.Also note that other cards could be used to make the "Three of a Kind" hand.
Input: ranks =[10,10,2,12,9], suits =["a","b","c","a","d"]Output: "Pair"Explanation: The hand with the first and second card consists of 2 cards with the same rank, so we have a "Pair".Note that we cannot make a "Flush" or a "Three of a Kind".
We need to check for the best poker hand in the order: Flush > Three of a Kind > Pair > High Card. If all suits are the same, it’s a Flush. Otherwise, count the frequency of each rank to check for Three of a Kind or Pair.
classSolution {
public String bestHand(int[] ranks, char[] suits) {
boolean flush =true;
for (char s : suits) if (s != suits[0]) flush =false;
if (flush) return"Flush";
Map<Integer, Integer> cnt =new HashMap<>();
for (int r : ranks) cnt.put(r, cnt.getOrDefault(r, 0) + 1);
int mx = 0;
for (int v : cnt.values()) mx = Math.max(mx, v);
if (mx >= 3) return"Three of a Kind";
if (mx == 2) return"Pair";
return"High Card";
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution {
funbestHand(ranks: IntArray, suits: CharArray): String {
if (suits.all { it== suits[0] }) return"Flush"val cnt = ranks.groupingBy { it }.eachCount()
val mx = cnt.values.maxOrNull() ?:0returnwhen {
mx >=3->"Three of a Kind" mx ==2->"Pair"else->"High Card" }
}
}
1
2
3
4
5
6
7
8
9
10
11
12
classSolution:
defbestHand(self, ranks: list[int], suits: list[str]) -> str:
if all(s == suits[0] for s in suits):
return"Flush"from collections import Counter
cnt = Counter(ranks)
mx = max(cnt.values())
if mx >=3:
return"Three of a Kind"if mx ==2:
return"Pair"return"High Card"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
impl Solution {
pubfnbest_hand(ranks: Vec<i32>, suits: Vec<char>) -> String {
if suits.iter().all(|&s| s == suits[0]) {
return"Flush".to_string();
}
letmut cnt = std::collections::HashMap::new();
for&r in&ranks {
*cnt.entry(r).or_insert(0) +=1;
}
let mx =*cnt.values().max().unwrap();
if mx >=3 {
"Three of a Kind".to_string()
} elseif mx ==2 {
"Pair".to_string()
} else {
"High Card".to_string()
}
}
}