Stone Game VII — LeetCode 1690 Python Solution

MediumArrayMathDynamic ProgrammingGame Theory
Problem
#1690
Reading time
3 min

The problem

Alice and Bob take turns playing a game, with Alice starting first. There are n stones arranged in a row.

Example

Input
stones = [5,3,1,4,2]
Output
6
Explanation
- Alice removes 2 and gets 5 + 3 + 1 + 4 = 13 points. Alice = 13, Bob = 0, stones = [5,3,1,4].

Python solution

Python
class Solution:
    def stoneGameVII(self, stones: List[int]) -> int:
        @cache
        def dfs(i: int, j: int) -> int:
            if i > j:
                return 0
            a = s[j + 1] - s[i + 1] - dfs(i + 1, j)
            b = s[j] - s[i] - dfs(i, j - 1)
            return max(a, b)

        s = list(accumulate(stones, initial=0))
        ans = dfs(0, len(stones) - 1)
        dfs.cache_clear()
        return ans

Complexity

MeasureComplexity
TimeO(n^2)
SpaceO(n^2) auxiliary

Pattern: Dynamic Programming

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