MediumNo. 1690

Stone Game VII — LeetCode 1690 Python Solution

Topics
Array, Math, Dynamic Programming, Game Theory
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

PythonSolution
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

Time
O(n2)
Space · auxiliary
O(n2)

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

Related problems
No.ProblemDifficulty
0877Stone GameMedium
0486Predict the WinnerMedium
1140Stone Game IIMedium
1406Stone Game IIIHard
1563Stone Game VHard
1728Cat and Mouse IIHard

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(n2).

What is the space complexity of LeetCode 1690. Stone Game VII?

The Python solution on this page uses O(n2) 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.

Free to download. Check it runs on your machine, then pick a plan.