Python 1140.py
class Solution:
def stoneGameII(self, piles: List[int]) -> int:
size = len(piles)
total = sum(piles)
remain = [] # stones left after reaching this position
for p in piles:
remain.append(total)
total -= p
@cache
def deeper(pos, m):
# take all (but works without this, too)
if pos + 2 * m >= size:
return remain[pos]
return remain[pos] - min(deeper(pos + take, max(m, take)) for take in range(1, 2 * m + 1))
return deeper(0, 1)
Difficulty
and has an acceptance rate of about 68% (100k+ submissions).
Typical patterns to solve this problem:
- Array
- Dynamic Programming
- Game Theory
- Math
- Prefix Sum
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 two-player stone-picking game by using a depth-first search with memoization. The algorithm computes the maximum number of stones the first player can obtain when both participants play optimally. It transforms the original problem into a series of sub-problems that ask, for a given position and a current limit M, how many stones the current player can secure from that point onward.
Core Logic
Preparing the auxiliary array
The code first determines the length of the pile list and the total number of stones. It then builds an auxiliary array remain where each entry records the number of stones that are still on the table when the game reaches the corresponding index. This pre-computation enables constant-time look-ups of the remaining stones during recursion.
size = len(piles)
total = sum(piles)
remain = [] # stones left after reaching this position
for p in piles:
remain.append(total)
total -= p
Recursive decision function
A nested function deeper is defined and decorated with @cache to memoize results for each (pos, m) pair. The parameters pos and m represent the current index in the pile list and the current maximum number of piles that may be taken, respectively.
@cache
def deeper(pos, m):
# take all (but works without this, too)
if pos + 2 * m >= size:
return remain[pos]
return remain[pos] - min(
deeper(pos + take, max(m, take))
for take in range(1, 2 * m + 1)
)
The base case checks whether the remaining piles can be taken in a single move. If pos + 2 * m reaches or exceeds the total number of piles, the current player can claim all stones left, which is exactly remain[pos].
When the base case does not apply, the function evaluates every legal take amount from 1 up to 2 * m. For each possible take, it recursively computes the opponent’s optimal outcome from the new position pos + take with an updated limit max(m, take). The current player’s gain is the total stones left (remain[pos]) minus the smallest value the opponent can force, which corresponds to the worst case for the current player. The min expression captures the opponent’s optimal counter-play.
Entry point
The public method simply invokes the recursive helper starting from the first pile with an initial limit of 1.
return deeper(0, 1)
Edge Cases Handled
The base-case condition if pos + 2 * m >= size: gracefully handles scenarios where the remaining number of piles is less than or equal to the maximum allowable take. In such situations the player can collect all remaining stones without further recursion, preventing out-of-range indexing and unnecessary deeper calls.
When the input list piles is empty, size becomes 0. The loop that builds remain does not execute, and the recursive function is never called because the initial call deeper(0, 1) immediately satisfies the base case (0 + 2 * 1 >= 0). The function returns remain[0], which is not defined, but the problem constraints guarantee at least one pile, so the code operates correctly within its intended domain.
If the pile values contain zeros, the remain array still correctly reflects the cumulative sum, and the recursion proceeds without special treatment because the decision logic depends only on indices and limits, not on individual pile values.
Performance Optimizations
The most significant optimization is the use of Python’s functools.cache decorator on the recursive function. By caching the result of each (pos, m) pair, the algorithm avoids recomputing identical sub-problems, turning an exponential search space into a polynomial one. This memoization ensures that each distinct state is evaluated at most once.
The pre-computed remain array eliminates the need to sum slices of the original list during recursion. Accessing remain[pos] provides the total stones left from any position in constant time, which reduces the overhead of repeated aggregation.
The early exit condition that checks whether the current player can take all remaining piles (pos + 2 * m >= size) prevents unnecessary iteration over the full range of possible takes when the outcome is already determined. This short-circuit saves both function call overhead and the generation of the comprehension that would otherwise evaluate many recursive branches.
By combining memoization, pre-computed cumulative sums, and an early termination clause, the implementation achieves efficient execution even for larger inputs while preserving the clarity of the recursive formulation.
ELI5 - Simplified Explanation
Imagine there is a long row of stone piles waiting on the floor. Two friends take turns picking up some of these piles to keep. Each friend wants to grab as many stones as they can.
At the start, there is a special rule for how many piles can be picked up. As the game goes on, this rule changes based on how many piles were taken just before. To figure out the best way to win, the computer looks ahead at all the different choices. It pretends to play the whole game over and over in its head.
The piece of code called deeper acts like a brain looking into the future. It checks every possible move to see what happens next. It subtracts what the other friend would take from the total amount of stones that are left. By doing this, the code finds the perfect number of stones to pick so that the first friend gathers the most possible prizes. It keeps track of the answers it already found so it does not have to do the same hard thinking twice. Eventually, it finds the biggest pile of stones that the first person can collect.
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 | ||||||
| leetcode.ca | C++ | Java | Python | Go | TS | |||
| Progiez | C++ | Java | Python | |||||
| github | BigEggStudy | C# | ||||||
| black-shadows | C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JS | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| BigEggStudy | C# | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| JoshCrozier | JavaScript | |||||||
| keineahnung2345 | C++ | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| varunu28 | Java | |||||||
| wisdompeak | C++ | |||||||
| withaarzoo | C++ |
Videos
Solved On The Same Day
- problem 1959: Minimum Total Space Wasted With K Resizing Operations
- problem 2211: Count Collisions on a Road
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