移除石子的最大得分【LC1753】
You are playing a solitaire game with three piles of stones of sizes
a,b, andcrespectively. Each turn you choose two different non-empty piles, take one stone from each, and add1point to your score. The game stops when there are fewer than two non-empty piles (meaning there are no more available moves).Given three integers
a,b, andc, return the *maximum* score you can get.
就是说 做出来了也觉得很amazing
-
思路:找找规律,贪心一下
局部最优:尽可能多匹配几次
全局最优:使最终得分最大
- 当对a,b,ca,b,ca,b,c进行升序排序后,如果a+b≥ca+b\ge ca+b≥c,应先优先让aaa和bbb去匹配,匹配的次数为a+b−ca+b-ca+b−c,得分为count=⌈(a+b−c)/2⌉count=\lceil (a+b-c)/2 \rceilcount=⌈(a+b−c)/2⌉
- 当a+b<ca+b\lt ca+b<c时,最多只能取a+ba+ba+b个石头
- 最终的得分即为count+a+bcount+a+bcount+a+b
-
实现
class Solution { public int maximumScore(int a, int b, int c) { int[] stones = {a, b ,c}; Arrays.sort(stones); a = stones[0]; b = stones[1]; c = stones[2]; int count = 0; // 先取ab,使a + b <= c while (a + b > c){ count++; a--; b--; } // 先取ac,再取bc return count + a + b; } }class Solution { public int maximumScore(int a, int b, int c) { int[] stones = {a, b ,c}; Arrays.sort(stones); a = stones[0]; b = stones[1]; c = stones[2]; int count = 0; // 先取ab,使a + b <= c if (a + b >= c){ count = (int)Math.ceil((a + b -c) / 2.0); a -= count; b -= count; } // 先取ac,再取bc return count + a + b; } }-
复杂度
- 时间复杂度:O(1)O(1)O(1)
- 空间复杂度:O(1)O(1)O(1)
-

本文介绍了一个独享纸牌游戏的策略问题,玩家有三堆不同大小的石头,每次可以从两堆中各取一块,得分加一,直到剩下少于两堆非空石头。关键在于找到最佳取石顺序以最大化得分。通过排序和贪心策略,当两堆石头之和大于第三堆时,优先取这两堆,否则按顺序取石,直至无法继续。该策略保证了全局最优解,且算法复杂度为常数级。

被折叠的 条评论
为什么被折叠?



