Python 1690.py
class Solution:
def stoneGameVII(self, stones: List[int]) -> int:
# prefix sum
prefix = [ 0 ]
for s in stones:
prefix.append(prefix[-1] + s)
# up to one million different parameter => Python's caching has high memory usage
# therefore I create my own caching
size = len(stones)
cache = []
for i in range(size):
cache.append([ -1 ] * i) # left < right, allocate only what we actually need
def deeper(left, right):
if left == right:
return 0
# lookup previous results
known = cache[right][left]
if known > -1:
return known
# sum
total = prefix[right + 1] - prefix[left]
# remove on the left side
one = (total - stones[left ]) - deeper(left + 1, right)
# remove on the right side
two = (total - stones[right]) - deeper(left, right - 1)
# go for the win !
cache[right][left] = best = max(one, two)
return best
return deeper(0, len(stones) - 1)
Difficulty
and has an acceptance rate of about 59% (70k+ 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 implementation solves the two-player “Stone Game VII” problem by computing the maximum possible difference in scores when both players play optimally. It uses a depth-first recursion with memoization to explore all sub-intervals of the stone array, while a prefix-sum array provides constant-time range sums. The result is the value returned from the recursive helper when the full interval [0, n-1] is processed.
Key Steps
The first phase builds a prefix-sum array that stores the cumulative total of stones up to each index. This enables fast computation of the sum of any sub-array without iterating over the elements each time.
prefix = [0]
for s in stones:
prefix.append(prefix[-1] + s)
Next, a custom triangular cache is allocated. For an interval [left, right] the cache is accessed as cache[right][left]. Because left is always less than right for non-trivial intervals, only the needed lower-triangular part of the matrix is created, saving memory compared with a full n × n table.
size = len(stones)
cache = []
for i in range(size):
cache.append([-1] * i) # allocate only entries where left < right
The core of the algorithm is the recursive function deeper(left, right). It first checks the base case where the interval contains a single stone; in that situation no further points can be earned, so the function returns 0.
if left == right:
return 0
If the result for the current interval has already been computed, the cached value is returned immediately, avoiding repeated work.
known = cache[right][left]
if known > -1:
return known
The total sum of stones in the current interval is obtained in constant time using the prefix array.
total = prefix[right + 1] - prefix[left]
Two possible moves are evaluated: removing the leftmost stone or removing the rightmost stone. After a removal, the opponent’s optimal response is subtracted from the remaining sum, because the game is zero-sum. The recursion therefore computes the net advantage for the current player for each choice.
one = (total - stones[left]) - deeper(left + 1, right)
two = (total - stones[right]) - deeper(left, right - 1)
The best of the two options is stored in the cache and returned.
cache[right][left] = best = max(one, two)
return best
Finally, the recursion is launched on the full range of stones.
return deeper(0, len(stones) - 1)
Edge Cases
When the input list contains only one stone, the initial call reaches the base case left == right immediately, and the function returns 0, correctly reflecting that no points can be taken. The triangular cache allocation also gracefully handles this situation because the inner list for i = 0 is empty, and the lookup cache[0][0] is never performed.
If the stones array is empty (which is not a valid input for the original problem), the code would attempt to access stones[0] during cache creation, but the problem constraints guarantee at least one element, so the implementation safely assumes a non-empty list.
The recursion correctly handles intervals where the left and right indices converge after several moves, always falling back to the base case and preventing out-of-range accesses.
Performance Optimizations
The prefix-sum array eliminates the need to recompute interval sums during each recursive call, turning what would be an O(length) operation into O(1).
A custom cache is used instead of Python’s built-in functools.lru_cache. By constructing a triangular list of lists, the implementation stores only the necessary entries where left < right. This reduces memory consumption dramatically for large inputs, because the number of stored states is n·(n-1)/2 rather than n².
Direct indexing into the cache (cache[right][left]) avoids the overhead of dictionary lookups that a typical memoization decorator would incur.
The recursion is tail-recursive in the sense that each call makes at most two further calls, and the memoization ensures that each distinct interval is evaluated only once, preventing exponential blow-up.
Overall, the combination of prefix sums, a space-efficient cache layout, and explicit memoization yields a solution that scales well to the maximum input size allowed by the problem constraints.
ELI5 - Simplified Explanation
Imagine a long row of colorful stones laid out on the floor. Each stone has a secret number written on the bottom. Two friends are taking turns picking a stone from either the very beginning or the very end of the line. Every time a stone is picked, the game calculates a score based on the sum of all the stones remaining in that row. The goal is to make the best possible choices to keep the score as high as possible.
The code starts by making a quick helper list that keeps track of the running total of all the numbers. This makes it super fast to figure out the sum of any chunk of stones without having to count them one by one every single time. Because there are so many different combinations to look at, the code builds a little notebook called a cache to write down the best answers it finds. Before doing any hard thinking, it peeks at this notebook to see if it already figured out the answer for a specific row of stones.
When it is the turn to choose, the code looks at two options. It tries picking the stone at the left end, and then it tries picking the stone at the right end. It looks ahead to see what happens next in both cases by calling itself over and over. By comparing the results, it picks the move that leads to the biggest score. After checking everything, it writes that best choice into the notebook so it never has to do the same work twice. It keeps doing this until all the stones are gone and the winner is decided.
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++ | Python | Java | TS | |||
| WalkCCC | C++ | Java | ||||||
| leetcode.ca | C++ | Python | Java | Go | TS | |||
| Progiez | C++ | Python | Java | |||||
| github | black-shadows | C++ | ||||||
| charles-wangkai | Java | |||||||
| everthis | JS | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JS | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ | |||||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||||
| WalkCCC | C++, Java | |||||||
| leetcode.ca | C++, Go, Java, Python, TypeScript | |||||||
| Progiez | C++, Java, Python | |||||||
| black-shadows | C++, C++ | |||||||
| charles-wangkai | Java | |||||||
| everthis | JavaScript | |||||||
| fsq | C++ | |||||||
| halfrost | Go | |||||||
| JoshCrozier | JavaScript | |||||||
| lkwq007 | Python | |||||||
| MacJim | C++ | |||||||
| suxrobGM | C# | |||||||
| trung-hn | Python | |||||||
| wisdompeak | C++ |
Videos
Similar Problems
- problem 1686: Stone Game VI
- problem 1770: Maximum Score from Performing Multiplication Operations
- problem 1872: Stone Game VIII
Solved On The Same Day
- problem 1621: Number of Sets of K Non-Overlapping Line Segments
- problem 1774: Closest Dessert Cost
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