Stone Game II — LeetCode 1140 Python Solution

MediumArrayMathDynamic ProgrammingGame TheoryPrefix Sum
Problem
#1140
Pattern
Prefix Sum
Reading time
2 min

The problem

Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].

Python solution

Python
class Solution:
    def stoneGameII(self, piles: List[int]) -> int:
        @cache
        def dfs(i, m):
            if m * 2 >= n - i:
                return s[n] - s[i]
            return max(
                s[n] - s[i] - dfs(i + x, max(m, x)) for x in range(1, m << 1 | 1)
            )

        n = len(piles)
        s = list(accumulate(piles, initial=0))
        return dfs(0, 1)

Complexity

MeasureComplexity
TimeO(n^3)
SpaceO(n^2) auxiliary

Pattern: Prefix Sum

Precompute running totals once so any range query becomes a single subtraction. LeetCode 1140. Stone Game II 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 1140. Stone Game II?
LeetCode 1140. Stone Game II is rated Medium on LeetCode.
What is the time complexity of LeetCode 1140. Stone Game II?
The Python solution on this page runs in O(n^3).
What is the space complexity of LeetCode 1140. Stone Game II?
The Python solution on this page uses O(n^2) auxiliary space.
What topics does LeetCode 1140. Stone Game II cover?
LeetCode 1140. Stone Game II 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