MediumNo. 1140

Stone Game II — LeetCode 1140 Python Solution

Pattern
Prefix Sum
Topics
Array, Math, Dynamic Programming, Game Theory, 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

PythonSolution
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

Time
O(n3)
Space · auxiliary
O(n2)

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

Related problems
No.ProblemDifficulty
0877Stone GameMedium
1872Stone Game VIIIHard
0486Predict the WinnerMedium
1406Stone Game IIIHard
1524Number of Sub-arrays With Odd SumMedium
1563Stone Game VHard

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(n3).

What is the space complexity of LeetCode 1140. Stone Game II?

The Python solution on this page uses O(n2) 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.

Free to download. Check it runs on your machine, then pick a plan.