Python 1406.py
class Solution:
def stoneGameIII(self, stoneValue: List[int]) -> str:
@cache
def deeper(pos):
if pos >= len(stoneValue):
return 0
take = stoneValue[pos]
best = take - deeper(pos + 1)
for i in range(pos + 1, pos + 2+1):
if i < len(stoneValue):
take += stoneValue[i]
best = max(best, take - deeper(i + 1))
return best
result = deeper(0)
if result == 0:
return "Tie"
return "Alice" if result > 0 else "Bob"
Difficulty
and has an acceptance rate of about 63% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Game Theory
- Math
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided implementation solves the “Stone Game III” problem using a recursive depth-first search with memoization. The core idea is to compute, for each starting position in the array, the maximum net score a player can achieve assuming optimal play from both sides. The recursion returns the difference between the current player’s total and the opponent’s total from that position onward. The final sign of this difference determines whether Alice wins, Bob wins, or the game ends in a tie.
Key Steps
The algorithm begins by defining a cached helper function deeper. The base case checks whether the current index has moved beyond the end of the stoneValue list; in that situation the net contribution is zero because no stones remain to be taken.
@cache
def deeper(pos):
if pos >= len(stoneValue):
return 0
The first move considered is taking a single stone at the current position. The value of that stone is stored in take, and the provisional best net score is computed as the value taken minus the opponent’s optimal response from the next position.
take = stoneValue[pos]
best = take - deeper(pos + 1)
A loop then explores the two-stone and three-stone take options. For each additional stone that stays within bounds, the cumulative take is updated, and the algorithm evaluates the net score if the player stops after that many stones. The max operation ensures that the best achievable net difference is retained.
for i in range(pos + 1, pos + 2+1):
if i < len(stoneValue):
take += stoneValue[i]
best = max(best, take - deeper(i + 1))
After all legal moves from the current position have been examined, the helper returns the optimal net score for that position.
return best
The top-level call deeper(0) yields the net advantage for the player who starts the game (Alice). The final conditional translates the numeric result into the required string output.
result = deeper(0)
if result == 0:
return "Tie"
return "Alice" if result > 0 else "Bob"
Edge Cases
When the input list is empty, the base case of deeper is triggered immediately, returning zero. Consequently the outer logic classifies the outcome as a tie, which correctly reflects that no player can obtain any points.
If the list contains fewer than three elements, the loop that attempts to take up to three stones gracefully handles the situation because the if i < len(stoneValue) guard prevents out-of-range access. For a single-element list, only the first take assignment is used; for a two-element list, the loop executes once, adding the second stone and evaluating the two-stone take. The algorithm never attempts to read beyond the array bounds.
Negative stone values are also accommodated. Since the recursion works with the raw sum of taken stones, a negative take can reduce the net score, and the max comparison still selects the move that yields the highest net advantage, even if that advantage is negative. This behavior correctly models scenarios where all remaining stones have negative values, forcing a player to minimize loss.
When the cumulative sum of stones from a certain position onward is zero, the recursion may encounter multiple paths that lead to the same net result. The memoization ensures that each position is evaluated only once, so repeated identical subproblems do not cause redundant computation.
Performance Optimizations
The most significant optimization is the use of the @cache decorator on the recursive helper. By storing the result of deeper(pos) for each distinct pos, the algorithm eliminates exponential recomputation of overlapping subproblems. Each array index is processed a single time, and subsequent calls retrieve the pre-computed value in constant time.
The loop that iterates over possible take lengths is bounded to at most two additional iterations (for taking two or three stones). This tight bound keeps the per-call work minimal while still covering all legal moves defined by the game rules.
The implementation avoids constructing auxiliary data structures such as prefix sums or explicit DP tables. By directly using the recursion and caching, the code maintains a compact memory footprint, storing only the cached results for each index and a few scalar variables per call.
The final decision logic (if result == 0, return "Alice" if result > 0 else "Bob") performs a single comparison to map the numeric outcome to the required string, avoiding any unnecessary branching or additional calculations.
ELI5 - Simplified Explanation
Imagine a long row of yummy candies laid out on a table. Two players take turns picking up candies from the front of the line. Each player can decide to grab one, two, or three candies at once. The goal is to collect more candy than the other person.
The code works like a very smart thinking machine that looks at all the possible moves. It imagines every choice someone could make and then thinks about what the next person would do in response. It keeps doing this over and over until there are no candies left, like planning out a perfect move in a game of checkers.
The part called deeper is the smart machine looking ahead. It starts at the very first candy and asks what happens if it takes one, two, or three. It then subtracts what the next person would get from what it gathers itself to see the difference in points. By doing this for the whole row, the computer compares the scores at the end. After checking every single way the game could go, the code compares the final totals. If the number is bigger than zero, the person who went first is the winner. If the number is smaller, the second person wins. If the numbers match perfectly, it ends in a tie.
Code Quality
Complexity Analysis
As a rule of thumb, the maximum input size for one second execution time is
- factorial: up to 10 elements
- exponential: up to 20 elements
- polynomial: a few thousand elements
- loglinear: up to 100,000 elements
- linear: a few million elements
- logarithmic: a billion elements
- constant: practically unlimited
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||||
|---|---|---|---|---|---|---|---|---|
| author | solutions | |||||||
| www | AlgoMonster | C++ | Java | Python | TS | |||
| WalkCCC | C++ | Java | Python | |||||
| leetcode.ca | C++ | Java | Python | Go | Rust | TS | ||
| Progiez | C++ | Java | Python | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| FelixFan1122 | Java | |||||||
| fsq | C++ | |||||||
| gouthampradhan | Java | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| muhammadfarhankt | Go | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Python, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, Rust, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| FelixFan1122 | Java | |||||||
| fsq | C++ | |||||||
| gouthampradhan | Java | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| muhammadfarhankt | Go | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 598: Range Addition II
- problem 653: Two Sum IV - Input is a BST
- problem 1470: Shuffle the Array
- problem 1512: Number of Good Pairs
- problem 1920: Build Array from Permutation
- problem 1929: Concatenation of Array
- problem 396: Rotate Function
- problem 877: Stone Game
- problem 1033: Moving Stones Until Consecutive
- problem 2396: Strictly Palindromic Number
- problem 1402: Reducing Dishes
- problem 1463: Cherry Pickup II
- problem 1510: Stone Game IV
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality