最多牌组数
难度:
标签:
题目描述
English description is not available for the problem. Please switch to Chinese.
代码结果
运行时间: 387 ms, 内存: 19.7 MB
import java.util.*;
import java.util.stream.Collectors;
/**
* This method finds the maximum number of valid Mahjong groups (either sequences or triplets)
* that can be formed from the given tiles using Java Streams.
*
* @param tiles an array of integers representing the Mahjong tiles
* @return the maximum number of valid groups
*/
public class MahjongGroupsStream {
public static int maxGroups(int[] tiles) {
// Count the frequency of each tile
Map<Integer, Long> tileCount = Arrays.stream(tiles)
.boxed()
.collect(Collectors.groupingBy(e -> e, Collectors.counting()));
List<Integer> sortedTiles = Arrays.stream(tiles)
.boxed()
.sorted()
.collect(Collectors.toList());
int groups = 0;
for (int tile : sortedTiles) {
if (tileCount.get(tile) > 0) {
// Try to form a triplet (3 of the same)
if (tileCount.get(tile) >= 3) {
tileCount.put(tile, tileCount.get(tile) - 3);
groups++;
} else if (tileCount.get(tile) > 0 && tileCount.getOrDefault(tile + 1, 0L) > 0 && tileCount.getOrDefault(tile + 2, 0L) > 0) {
// Try to form a sequence (3 consecutive numbers)
tileCount.put(tile, tileCount.get(tile) - 1);
tileCount.put(tile + 1, tileCount.get(tile + 1) - 1);
tileCount.put(tile + 2, tileCount.get(tile + 2) - 1);
groups++;
}
}
}
return groups;
}
public static void main(String[] args) {
int[] tiles1 = {2, 2, 2, 3, 4};
int[] tiles2 = {2, 2, 2, 3, 4, 1, 3};
System.out.println(maxGroups(tiles1)); // Output: 1
System.out.println(maxGroups(tiles2)); // Output: 2
}
}
解释
方法:
本题解采用动态规划的方法来决定最大牌组数。首先,使用Counter统计每张牌的数量。定义状态dp[i, j]表示当考虑到当前数字num时,并且(num+1)剩下i张,(num+2)剩下j张时,可以形成的最大组数。遍历每个数字num,对于每个num,我们查看可以使用当前num及其后两个数字(num+1和num+2)来形成多少组顺子。考虑到num, num+1, num+2可以组成的顺子数量,并更新状态。最后,dp字典中的最大值即为答案。
时间复杂度:
O(n log n)
空间复杂度:
O(n)
代码细节讲解
🦆
如何确保动态规判断的`dp[i, j]`是有效的状态,能够覆盖所有组合情况?
▷🦆
在动态规划的转移方程中,为什么选择`(x - i - k) // 3 + k`作为新状态的计算方式?
▷🦆
对于处理边界条件,当`num+1`或`num+2`不存在于`tiles`中时,如何处理这些情况?
▷