Welcome to Subscribe On Youtube
3222. Find the Winning Player in Coin Game
Description
You are given two positive integers x
and y
, denoting the number of coins with values 75 and 10 respectively.
Alice and Bob are playing a game. Each turn, starting with Alice, the player must pick up coins with a total value 115. If the player is unable to do so, they lose the game.
Return the name of the player who wins the game if both players play optimally.
Example 1:
Input: x = 2, y = 7
Output: "Alice"
Explanation:
The game ends in a single turn:
- Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.
Example 2:
Input: x = 4, y = 11
Output: "Bob"
Explanation:
The game ends in 2 turns:
- Alice picks 1 coin with a value of 75 and 4 coins with a value of 10.
- Bob picks 1 coin with a value of 75 and 4 coins with a value of 10.
Constraints:
1 <= x, y <= 100
Solutions
Solution 1: Mathematics
Since each round of operation consumes $2$ coins valued at $75$ and $8$ coins valued at $10$, we can calculate the number of rounds $k = \min(x / 2, y / 8)$, and then update the values of $x$ and $y$, where $x$ and $y$ are the remaining number of coins after $k$ rounds of operations.
If $x > 0$ and $y \geq 4$, then Alice can continue the operation, and Bob loses, return “Alice”; otherwise, return “Bob”.
The time complexity is $O(1)$, and the space complexity is $O(1)$.
-
class Solution { public String losingPlayer(int x, int y) { int k = Math.min(x / 2, y / 8); x -= k * 2; y -= k * 8; return x > 0 && y >= 4 ? "Alice" : "Bob"; } }
-
class Solution { public: string losingPlayer(int x, int y) { int k = min(x / 2, y / 8); x -= k * 2; y -= k * 8; return x && y >= 4 ? "Alice" : "Bob"; } };
-
class Solution: def losingPlayer(self, x: int, y: int) -> str: k = min(x // 2, y // 8) x -= k * 2 y -= k * 8 return "Alice" if x and y >= 4 else "Bob"
-
func losingPlayer(x int, y int) string { k := min(x/2, y/8) x -= 2 * k y -= 8 * k if x > 0 && y >= 4 { return "Alice" } return "Bob" }
-
function losingPlayer(x: number, y: number): string { const k = Math.min((x / 2) | 0, (y / 8) | 0); x -= k * 2; y -= k * 8; return x && y >= 4 ? 'Alice' : 'Bob'; }