leet-code/src/main/java/leetcode/editor/cn/StoneGameIx.java
2022-01-20 10:47:43 +08:00

81 lines
2.9 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//Alice 和 Bob 再次设计了一款新的石子游戏。现有一行 n 个石子,每个石子都有一个关联的数字表示它的价值。给你一个整数数组 stones ,其中
//stones[i] 是第 i 个石子的价值。
//
// Alice 和 Bob 轮流进行自己的回合Alice 先手。每一回合,玩家需要从 stones 中移除任一石子。
//
//
// 如果玩家移除石子后,导致 所有已移除石子 的价值 总和 可以被 3 整除,那么该玩家就 输掉游戏 。
// 如果不满足上一条,且移除后没有任何剩余的石子,那么 Bob 将会直接获胜(即便是在 Alice 的回合)。
//
//
// 假设两位玩家均采用 最佳 决策。如果 Alice 获胜,返回 true ;如果 Bob 获胜,返回 false 。
//
//
//
// 示例 1
//
//
//输入stones = [2,1]
//输出true
//解释:游戏进行如下:
//- 回合 1Alice 可以移除任意一个石子。
//- 回合 2Bob 移除剩下的石子。
//已移除的石子的值总和为 1 + 2 = 3 且可以被 3 整除。因此Bob 输Alice 获胜。
//
//
// 示例 2
//
//
//输入stones = [2]
//输出false
//解释Alice 会移除唯一一个石子,已移除石子的值总和为 2 。
//由于所有石子都已移除,且值总和无法被 3 整除Bob 获胜。
//
//
// 示例 3
//
//
//输入stones = [5,1,2,4,3]
//输出false
//解释Bob 总会获胜。其中一种可能的游戏进行方式如下:
//- 回合 1Alice 可以移除值为 1 的第 2 个石子。已移除石子值总和为 1 。
//- 回合 2Bob 可以移除值为 3 的第 5 个石子。已移除石子值总和为 = 1 + 3 = 4 。
//- 回合 3Alices 可以移除值为 4 的第 4 个石子。已移除石子值总和为 = 1 + 3 + 4 = 8 。
//- 回合 4Bob 可以移除值为 2 的第 3 个石子。已移除石子值总和为 = 1 + 3 + 4 + 2 = 10.
//- 回合 5Alice 可以移除值为 5 的第 1 个石子。已移除石子值总和为 = 1 + 3 + 4 + 2 + 5 = 15.
//Alice 输掉游戏因为已移除石子值总和15可以被 3 整除Bob 获胜。
//
//
//
//
// 提示:
//
//
// 1 <= stones.length <= 10⁵
// 1 <= stones[i] <= 10⁴
//
// Related Topics 贪心 数组 数学 计数 博弈 👍 50 👎 0
package leetcode.editor.cn;
//2029:石子游戏 IX
public class StoneGameIx {
public static void main(String[] args) {
Solution solution = new StoneGameIx().new Solution();
// TO TEST
}
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public boolean stoneGameIX(int[] stones) {
int[] counts = new int[3];
for (int stone : stones) {
counts[stone % 3]++;
}
return counts[0] % 2 == 0 ? counts[1] > 0 && counts[2] > 0 : Math.abs(counts[1] - counts[2]) > 2;
}
}
//leetcode submit region end(Prohibit modification and deletion)
}