Stone Game VII Problem
Description
LeetCode Problem 1690.
Alice and Bob take turns playing a game, with Alice starting first.
There are n stones arranged in a row. On each player's turn, they can remove either the leftmost stone or the rightmost stone from the row and receive points equal to the sum of the remaining stones' values in the row. The winner is the one with the higher score when there are no stones left to remove.
Bob found that he will always lose this game (poor Bob, he always loses), so he decided to minimize the score's difference. Alice's goal is to maximize the difference in the score.
Given an array of integers stones where stones[i] represents the value of the i^th stone from the left, return the difference in Alice and Bob's score if they both play optimally.
Example 1:
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].
- Bob removes 5 and gets 3 + 1 + 4 = 8 points. Alice = 13, Bob = 8, stones = [3,1,4].
- Alice removes 3 and gets 1 + 4 = 5 points. Alice = 18, Bob = 8, stones = [1,4].
- Bob removes 1 and gets 4 points. Alice = 18, Bob = 12, stones = [4].
- Alice removes 4 and gets 0 points. Alice = 18, Bob = 12, stones = [].
The score difference is 18 - 12 = 6.
Example 2:
Input: stones = [7,90,5,1,100,10,10,2]
Output: 122
Constraints:
n == stones.length2 <= n <= 10001 <= stones[i] <= 1000
Solution
Approach: Interval Dynamic Programming
Build a prefix sum array s, where s[i] is the total of the first i stones, so the sum of any range is one subtraction.
Let f[i][j] be the best score difference (current player minus the other) when only stones[i..j] remain. The answer is f[0][n - 1], and a single stone gives f[i][i] = 0 (removing it leaves nothing to score).
For i < j, the current player has two choices:
- Remove
stones[i]and score the rest,s[j + 1] - s[i + 1]; the opponent then plays on[i + 1, j], so the difference isa = s[j + 1] - s[i + 1] - f[i + 1][j]. - Remove
stones[j]and scores[j] - s[i], givingb = s[j] - s[i] - f[i][j - 1].
So f[i][j] = max(a, b). Fill the table with i going down from n - 2 and j going up from i + 1, so both smaller intervals are ready.
Complexity: O(n^2) time and O(n^2) space, where n is the number of stones.
from itertools import accumulate
class Solution:
def stoneGameVII(self, stones: List[int]) -> int:
n = len(stones)
s = list(accumulate(stones, initial=0))
f = [[0] * n for _ in range(n)]
for i in range(n - 2, -1, -1):
for j in range(i + 1, n):
a = s[j + 1] - s[i + 1] - f[i + 1][j]
b = s[j] - s[i] - f[i][j - 1]
f[i][j] = a if a > b else b
return f[0][n - 1]