MediumNo. 0464
Can I Win — LeetCode 464 Python Solution
- Pattern
- Bit Manipulation
- Topics
- Bit Manipulation, Memoization, Math, Dynamic Programming, Bitmask, Game Theory
- Reading time
- 3 min
- Source
- leetcode.com
The problem
In the "100 game" two players take turns adding, to a running total, any integer from 1 to 10. The player who first causes the running total to reach or exceed 100 wins.
Example
- Input
- maxChoosableInteger = 10, desiredTotal = 11
- Output
- false
- Explanation
- No matter which integer the first player choose, the first player will lose.
Python solution
class Solution:
def canIWin(self, maxChoosableInteger: int, desiredTotal: int) -> bool:
@cache
def dfs(mask: int, s: int) -> bool:
for i in range(1, maxChoosableInteger + 1):
if mask >> i & 1 ^ 1:
if s + i >= desiredTotal or not dfs(mask | 1 << i, s + i):
return True
return False
if (1 + maxChoosableInteger) * maxChoosableInteger // 2 < desiredTotal:
return False
return dfs(0, 0)Complexity
- Time
- O(2n)
- Space · auxiliary
- O(2n)
Pattern: Bit Manipulation
Use XOR, masks and the low-bit trick to replace whole data structures with an integer. LeetCode 464. Can I Win is filed here because LeetCode tags it Bit Manipulation and Bitmask, which is the vocabulary this hub collects.
The bit manipulation guide has the Python template for the pattern and the 194 LeetCode problems that use it.
Related problems
| No. | Problem | Difficulty |
|---|---|---|
| 0638 | Shopping Offers | Medium |
| 0698 | Partition to K Equal Sum Subsets | Medium |
| 0805 | Split Array With Same Average | Hard |
| 0913 | Cat and Mouse | Hard |
| 1659 | Maximize Grid Happiness | Hard |
| 1728 | Cat and Mouse II | Hard |
Frequently asked questions
- How hard is LeetCode 464. Can I Win?
LeetCode 464. Can I Win is rated Medium on LeetCode.
- What is the time complexity of LeetCode 464. Can I Win?
The Python solution on this page runs in O(2n).
- What is the space complexity of LeetCode 464. Can I Win?
The Python solution on this page uses O(2n) auxiliary space.
- What topics does LeetCode 464. Can I Win cover?
LeetCode 464. Can I Win is tagged Bit Manipulation, Memoization, Math, Dynamic Programming, Bitmask and Game Theory on LeetCode.