Stone Game — LeetCode 877 Python Solution

MediumArrayMathDynamic ProgrammingGame Theory
Problem
#877
Reading time
2 min

The problem

Alice and Bob play a game with piles of stones. There are an even number of piles arranged in a row, and each pile has a positive integer number of stones piles[i].

Example

Input
piles = [5,3,4,5]
Output
true
Explanation
Alice starts first, and can only take the first 5 or the last 5.

Python solution

Python
class Solution:
    def stoneGame(self, piles: List[int]) -> bool:
        @cache
        def dfs(i: int, j: int) -> int:
            if i > j:
                return 0
            return max(piles[i] - dfs(i + 1, j), piles[j] - dfs(i, j - 1))

        return dfs(0, len(piles) - 1) > 0

Complexity

MeasureComplexity
TimeO(n·m) (typical)
SpaceO(n·m) or optimized auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 877. Stone Game is filed here on both counts: the reference solution below belongs to the algorithm family this hub collects, and LeetCode tags it Dynamic Programming.

The dynamic programming guide has the Python template for the pattern and the 481 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 877. Stone Game?
LeetCode 877. Stone Game is rated Medium on LeetCode.
What topics does LeetCode 877. Stone Game cover?
LeetCode 877. Stone Game is tagged Array, Math, Dynamic Programming and Game Theory 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