问题描述
在一场经典的德州扑克游戏中,有一种牌型叫做“葫芦”。“葫芦”由五张牌组成,其中包括三张相同牌面值的牌 aa 和另外两张相同牌面值的牌 bb。如果两个人同时拥有“葫芦”,我们会优先比较牌 aa 的大小,若牌 aa 相同则再比较牌 bb 的大小。
在这个问题中,我们对“葫芦”增加了一个限制:组成“葫芦”的五张牌牌面值之和不能超过给定的最大值 maxmax。牌面值的大小规则为:A > K > Q > J > 10 > 9 > ... > 2,其中 A 的牌面值为1,K 为13,依此类推。
给定一组牌,你需要找到符合规则的最大的“葫芦”组合,并输出其中三张相同的牌面和两张相同的牌面。如果找不到符合条件的“葫芦”,则输出 “0, 0”。
测试样例
样例1:
输入:
n = 9, max = 34, array = [6, 6, 6, 8, 8, 8, 5, 5, 1]
输出:[8, 5]
样例2:
输入:
n = 9, max = 37, array = [9, 9, 9, 9, 6, 6, 6, 6, 13]
输出:[6, 9]
样例3:
输入:
n = 9, max = 40, array = [1, 11, 13, 12, 7, 8, 11, 5, 6]
输出:[0, 0]
解题思路
我们将卡牌的数量映射到cardCount数组中,从cardCount中选数来进行牌面值的计算会简便很多。
具体步骤
- 遍历array数组,得到cardCount数组
- 双重遍历cardCount数组从中选择牌a、牌b来计算
卡面值totalSum - 需要注意的是,卡面值不能代表卡面大小,这里我们将1的
比较值赋值为14,方便进行比较
更新条件
- totalSum <= max
- a的比较值大于原先a的比较值就要更新
ora的比较值等于原先a的比较值但是b的比较值大于原先b的比较值
代码实现
public class Main {
public static int[] solution(int n, int max, int[] array) {
// Edit your code here
int[] result = {0, 0};
int[] cardCount = new int[14]; // Card values from 1 to 13, 0 unused
// Count occurrences of each card value
for (int card : array) {
cardCount[card]++;
}
int cardsum=0;
int curcardsum=0;
int carda=0;
int curcarda=0;
int curcardb=0;
int cardb=0;
// Find possible full houses
for (int a = 1; a <= 13; a++) {
if (cardCount[a] >= 3) { // At least three cards of 'a'
for (int b = 1; b <= 13; b++) {
if (b != a && cardCount[b] >= 2) { // Different cards 'a' and 'b'
int totalSum = 3 * a + 2 * b;
if(a==1){
carda=14;
} else carda=a;
if(b==1){
cardb=14;
}else cardb=b;
if (totalSum <= max&&(carda>curcarda||(carda==curcarda&&cardb>curcardb))) {
result[0] = a; // Update result
result[1] = b;
curcardsum=cardsum;
curcarda=carda;
curcardb=cardb;
}
}
}
}
}
return result;
}
public static void main(String[] args) {
// Add your test cases here
System.out.println(java.util.Arrays.equals(solution(9, 34, new int[]{6, 6, 6, 8, 8, 8, 5, 5, 1}), new int[]{8, 5}));
System.out.println(java.util.Arrays.equals(solution(9, 37, new int[]{9, 9, 9, 9, 6, 6, 6, 6, 13}), new int[]{6, 9}));
System.out.println(java.util.Arrays.equals(solution(9, 40, new int[]{1, 11, 13, 12, 7, 8, 11, 5, 6}), new int[]{0, 0}));
}
}