Stone Game VIII — LeetCode 1872 Python Solution

HardArrayMathDynamic ProgrammingGame TheoryPrefix Sum
Problem
#1872
Pattern
Prefix Sum
Reading time
2 min

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

MeasureComplexity
TimeO(n)
SpaceO(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.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview