MediumNo. 0877

Stone Game — LeetCode 877 Python Solution

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

PythonSolution
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

Time
O(n·m) (typical)
Space · auxiliary
O(n·m)or optimized

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

Related problems
No.ProblemDifficulty
1140Stone Game IIMedium
1406Stone Game IIIHard
1563Stone Game VHard
1690Stone Game VIIMedium
1872Stone Game VIIIHard
1510Stone Game IVHard

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.

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