#1510
Stone Game IV
HardMathDynamic ProgrammingGame TheoryDynamic ProgrammingGame Theory
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n√n) |
| Space | O(1) | O(n) |
💡
Intuition
Time O(n√n)Space O(n)
We can use dynamic programming to store the winning states for each number of stones. By building up from smaller numbers, we can determine if Alice can win with n stones by checking if she can force Bob into a losing state.
⚙️
Algorithm
3 steps- 1Step 1: Create a boolean array dp of size n+1, where dp[i] indicates if Alice can win with i stones.
- 2Step 2: Initialize dp[0] to false (no stones means Bob wins).
- 3Step 3: For each number of stones from 1 to n, check all square numbers and update dp[i] based on whether removing that square leads to a losing state for Bob.
solution.py10 lines
1def winnerSquareGame(n):
2 dp = [False] * (n + 1)
3 for i in range(1, n + 1):
4 j = 1
5 while j * j <= i:
6 if not dp[i - j * j]:
7 dp[i] = True
8 break
9 j += 1
10 return dp[n]ℹ
Complexity note: The time complexity is O(n√n) because for each of the n states, we are iterating through the square numbers up to √n, leading to a linear growth with respect to n and a logarithmic growth with respect to the number of squares.
- 1Alice can win if she can force Bob into a losing state.
- 2Dynamic programming helps in breaking down the problem into manageable subproblems.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.