Stone Game VIII — LeetCode 1872 Python Solution
HardArrayMathDynamic ProgrammingGame TheoryPrefix Sum
- Problem
- #1872
- Pattern
- Prefix Sum
- Reading time
- 2 min
- Source
- leetcode.com
The problem
Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row.
Example
- Input
- stones = [-1,2,-3,4,-5]
- Output
- 5
- Explanation
- - Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of
Python solution
Python
class Solution:
def stoneGameVIII(self, stones: List[int]) -> int:
@cache
def dfs(i: int) -> int:
if i >= len(stones) - 1:
return s[-1]
return max(dfs(i + 1), s[i] - dfs(i + 1))
s = list(accumulate(stones))
return dfs(1)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
Pattern: Prefix Sum
Precompute running totals once so any range query becomes a single subtraction. LeetCode 1872. Stone Game VIII is filed here because LeetCode tags it Prefix Sum, which is the vocabulary this hub collects.
The prefix sum guide has the Python template for the pattern and the 157 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 1872. Stone Game VIII?
- LeetCode 1872. Stone Game VIII is rated Hard on LeetCode.
- What is the time complexity of LeetCode 1872. Stone Game VIII?
- The Python solution on this page runs in O(n).
- What is the space complexity of LeetCode 1872. Stone Game VIII?
- The Python solution on this page uses O(n) auxiliary space.
- What topics does LeetCode 1872. Stone Game VIII cover?
- LeetCode 1872. Stone Game VIII is tagged Array, Math, Dynamic Programming, Game Theory and Prefix Sum on LeetCode.