#877
Stone Game
MediumArrayMathDynamic ProgrammingGame TheoryDynamic ProgrammingGame Theory
Approaches
Brute ForceOptimal
Complexity Comparison
| Brute Force | Optimal Solution★ | |
|---|---|---|
| Time | O(n²) | O(n²) |
| Space | O(1) | O(n²) |
💡
Intuition
Time O(n²)Space O(n²)
The optimal solution leverages dynamic programming to avoid redundant calculations. We use a DP table to store the maximum stones Alice can collect from any subarray of piles, ensuring we only compute each state once.
⚙️
Algorithm
3 steps- 1Step 1: Create a DP table where dp[i][j] represents the maximum stones Alice can collect from piles[i] to piles[j].
- 2Step 2: Initialize the table for single piles, where dp[i][i] = piles[i].
- 3Step 3: Fill the table for larger subarrays using the relation: dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1]).
solution.py10 lines
1def stoneGame(piles):
2 n = len(piles)
3 dp = [[0] * n for _ in range(n)]
4 for i in range(n):
5 dp[i][i] = piles[i]
6 for length in range(2, n + 1):
7 for i in range(n - length + 1):
8 j = i + length - 1
9 dp[i][j] = max(piles[i] - dp[i + 1][j], piles[j] - dp[i][j - 1])
10 return dp[0][n - 1] > 0ℹ
Complexity note: The time complexity remains O(n²) because we fill a DP table of size n x n. The space complexity is also O(n²) due to the storage of the DP table.
- 1Alice can always win if both play optimally due to the even number of piles.
- 2The game can be analyzed using dynamic programming to optimize decision-making.
Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.