MediumNo. 1690
Stone Game VII — LeetCode 1690 Python Solution
- Pattern
- Dynamic Programming
- Topics
- Array, Math, Dynamic Programming, Game Theory
- Reading time
- 3 min
- Source
- leetcode.com
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
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 ansComplexity
- 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
| No. | Problem | Difficulty |
|---|---|---|
| 0877 | Stone Game | Medium |
| 0486 | Predict the Winner | Medium |
| 1140 | Stone Game II | Medium |
| 1406 | Stone Game III | Hard |
| 1563 | Stone Game V | Hard |
| 1728 | Cat and Mouse II | Hard |
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.