移除石子的最大得分 Maximum Score From Removing Stones
LeetCode传送门移除石子的最大得分
题目
你正在玩一个单人游戏,面前放置着大小分别为 a、b 和 c 的 三堆 石子。
每回合你都要从两个 不同的非空堆 中取出一颗石子,并在得分上加 1 分。当存在 两个或更多 的空堆时,游戏停止。
给你三个整数 a 、b 和 c ,返回可以得到的 最大分数 。
You are playing a solitaire game with three piles of stones of sizes a, b, and c respectively. Each turn you choose two different non-empty piles, take one stone from each, and add 1 point 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, and c, return the maximum score you can get.
Example:
Input: a = 2, b = 4, c = 6
Output: 6
Explanation: The starting state is (2, 4, 6). One optimal set of moves is:
- Take from 1st and 3rd piles, state is now (1, 4, 5)
- Take from 1st and 3rd piles, state is now (0, 4, 4)
- Take from 2nd and 3rd piles, state is now (0, 3, 3)
- Take from 2nd and 3rd piles, state is now (0, 2, 2)
- Take from 2nd and 3rd piles, state is now (0, 1, 1)
- Take from 2nd and 3rd piles, state is now (0, 0, 0)
There are fewer than two non-empty piles, so the game ends. Total: 6 points.
Input: a = 4, b = 4, c = 6
Output: 7
Explanation: The starting state is (4, 4, 6). One optimal set of moves is:
- Take from 1st and 2nd piles, state is now (3, 3, 6)
- Take from 1st and 3rd piles, state is now (2, 3, 5)
- Take from 1st and 3rd piles, state is now (1, 3, 4)
- Take from 1st and 3rd piles, state is now (0, 3, 3)
- Take from 2nd and 3rd piles, state is now (0, 2, 2)
- Take from 2nd and 3rd piles, state is now (0, 1, 1)
- Take from 2nd and 3rd piles, state is now (0, 0, 0)
There are fewer than two non-empty piles, so the game ends. Total: 7 points.
Input: a = 1, b = 8, c = 8
Output: 8
Explanation: One optimal set of moves is to take from the 2nd and 3rd piles for 8 turns until they are empty.
After that, there are fewer than two non-empty piles, so the game ends.
Constraints:
1 <= a, b, c <= 10^5
思考线
解题思路
我们通过观察可以发现,只要我们满足至少两个数为0,则完成移除工作(这一步我们可以使用while循环来完成)
然后我们可以获取三个数中的最大值和最小值
若最小值为0 则直接返回剩下两个数中最小的数即可。
若不是0,则最小的数和最大的数各-1。每次移除石子我们都+1分。
根据上面思路我们完成代码如下:
function maximumScore(a: number, b: number, c: number): number {
let max = Math.max(a, b, c);
let min = Math.min(a, b, c);
let res = 0;
while ((a > 0 && b > 0) || (a > 0 && c > 0) || (b > 0 && c > 0)) {
if (min === 0) {
if (min === a) {
return res += Math.min(b, c)
}
if (min === b) {
return res += Math.min(a, c)
}
if (min === c) {
return res += Math.min(b, a)
}
}
if (min === a) {
a--
} else if (min === b) {
b--
} else if (min === c) {
c--
}
if (max === a) {
a--;
} else if (max === b) {
b--
} else if (max === c) c--;
max = Math.max(a, b, c);
min = Math.min(a, b, c);
res += 1;
}
return res;
};
这就是我对本题的解法,如果有疑问或者更好的解答方式,欢迎留言互动。