Stone Game — LeetCode 877 Python Solution
- Problem
- #877
- Pattern
- Dynamic Programming
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].
Example
- Input
- piles = [5,3,4,5]
- Output
- true
- Explanation
- Alice starts first, and can only take the first 5 or the last 5.
Python solution
class Solution:
def stoneGame(self, piles: List[int]) -> bool:
@cache
def dfs(i: int, j: int) -> int:
if i > j:
return 0
return max(piles[i] - dfs(i + 1, j), piles[j] - dfs(i, j - 1))
return dfs(0, len(piles) - 1) > 0Complexity
| Measure | Complexity |
|---|---|
| Time | O(n·m) (typical) |
| Space | O(n·m) or optimized auxiliary |
Pattern: Dynamic Programming
Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 877. Stone Game is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.
The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 877. Stone Game?
- LeetCode 877. Stone Game is rated Medium on LeetCode.
- What topics does LeetCode 877. Stone Game cover?
- LeetCode 877. Stone Game is tagged Array, Math, Dynamic Programming and Game Theory on LeetCode.