Stone Game III — LeetCode 1406 Python Solution

HardArrayMathDynamic ProgrammingGame Theory
Problem
#1406
Reading time
3 min

The problem

Alice and Bob continue their games with piles of stones. There are several stones arranged in a row, and each stone has an associated value which is an integer given in the array stoneValue.

Example

Input
stoneValue = [1,2,3,7]
Output
"Bob"
Explanation
Alice will always lose. Her best move will be to take three piles and the score become 6. Now the score of Bob is 7 and Bob wins.

Python solution

Python
class Solution:
    def stoneGameIII(self, stoneValue: List[int]) -> str:
        @cache
        def dfs(i: int) -> int:
            if i >= n:
                return 0
            ans, s = -inf, 0
            for j in range(3):
                if i + j >= n:
                    break
                s += stoneValue[i + j]
                ans = max(ans, s - dfs(i + j + 1))
            return ans

        n = len(stoneValue)
        ans = dfs(0)
        if ans == 0:
            return 'Tie'
        return 'Alice' if ans > 0 else 'Bob'

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Dynamic Programming

Define a state, write the transition, and stop recomputing the same subproblem. LeetCode 1406. Stone Game III 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 1406. Stone Game III?
LeetCode 1406. Stone Game III is rated Hard on LeetCode.
What is the time complexity of LeetCode 1406. Stone Game III?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1406. Stone Game III?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1406. Stone Game III cover?
LeetCode 1406. Stone Game III 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