HardNo. 1872
Stone Game VIII — LeetCode 1872 Python Solution
- Pattern
- Prefix Sum
- Topics
- Array, Math, Dynamic Programming, Game Theory, 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
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
- Time
- O(n)
- Space · auxiliary
- O(n)
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
| No. | Problem | Difficulty |
|---|---|---|
| 0877 | Stone Game | Medium |
| 1140 | Stone Game II | Medium |
| 0486 | Predict the Winner | Medium |
| 1406 | Stone Game III | Hard |
| 1524 | Number of Sub-arrays With Odd Sum | Medium |
| 1563 | Stone Game V | Hard |
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.