Leetcode #1406: Stone Game III
In this guide, we solve Leetcode #1406 Stone Game III in Python and focus on the core idea that makes the solution efficient.
You will see the intuition, the step-by-step method, and a clean Python implementation you can use in interviews.

Problem Statement
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.
Quick Facts
- Difficulty: Hard
- Premium: No
- Tags: Array, Math, Dynamic Programming, Game Theory
Intuition
The problem breaks into overlapping subproblems, so caching results prevents exponential repetition.
A carefully chosen DP state captures exactly what we need to build the final answer.
Approach
Define the DP state and recurrence, then compute states in the correct order.
Optionally compress space once the recurrence is clear.
Steps:
- Choose a DP state definition.
- Write the recurrence and base cases.
- Compute states in the correct order.
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
class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
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
The time complexity is , and the space complexity is . The space complexity is .
Edge Cases and Pitfalls
Watch for boundary values, empty inputs, and duplicate values where applicable. If the problem involves ordering or constraints, confirm the invariant is preserved at every step.
Summary
This Python solution focuses on the essential structure of the problem and keeps the implementation interview-friendly while meeting the constraints.