Find the Winning Player in Coin Game Problem
Description
LeetCode Problem 3222.
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
Solution
Approach: Mathematics
Every move takes 2 coins of value 75 and 8 coins of value 10, so the players can make k = min(x / 2, y / 8) full rounds without any problem. After those rounds x and y are reduced by 2k and 8k.
Then Alice moves if she still has a 75-coin and at least four 10-coins left (x > 0 and y >= 4); in that case Bob cannot move and loses, so the answer is "Alice". Otherwise the answer is "Bob".
Complexity: time O(1), space O(1).
class Solution:
def winningPlayer(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"