Stone Game II Problem
Description
LeetCode Problem 1140.
Alice and Bob continue their games with piles of stones. There are a number of piles arranged in a row, and each pile has a positive integer number of stones piles[i]. The objective of the game is to end with the most stones.
Alice and Bob take turns, with Alice starting first.
On each player's turn, that player can take all the stones in the first X remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X). Initially, M = 1.
The game continues until all the stones have been taken.
Assuming Alice and Bob play optimally, return the maximum number of stones Alice can get.
Example 1:
Input: piles = [2,7,9,4,4]
Output: 10
Explanation:
- If Alice takes one pile at the beginning, Bob takes two piles, then Alice takes 2 piles again. Alice can get 2 + 4 + 4 = 10 stones in total.
- If Alice takes two piles at the beginning, then Bob can take all three piles left. In this case, Alice get 2 + 7 = 9 stones in total.
So we return 10 since it's larger.
Example 2:
Input: piles = [1,2,3,4,5,100]
Output: 104
Constraints:
1 <= piles.length <= 1001 <= piles[i] <= 10^4
Solution
Approach: Memoized Game Search on (Start, M)
The game is zero-sum: all the stones get taken, so whatever the opponent ends up with, the current player does not. That gives a clean recursion. Let best(i, m) be the most stones the player to move can collect from the piles piles[i..] when the current value of M is m, and let suffix[i] be the total of piles[i..].
- If
i + 2m >= n, the player can take every remaining pile, sobest(i, m) = suffix[i]. Taking everything is optimal because all piles are positive. - Otherwise the player picks
xfrom1to2m. The opponent then plays fromi + xwithM = max(m, x)and collectsbest(i + x, max(m, x)); the current player gets the rest ofsuffix[i]. Sobest(i, m) = suffix[i] - min over x of best(i + x, max(m, x)).
The answer is best(0, 1). Many move sequences lead to the same state (i, m), so we memoize. There are at most n values of i and n values of m, and each state tries up to 2m moves.
Complexity: O(n3) time and O(n2) space for the memo table.
from functools import lru_cache
class Solution:
def stoneGameII(self, piles: List[int]) -> int:
n = len(piles)
suffix = [0] * (n + 1) # suffix[i]: stones in piles[i:]
for i in range(n - 1, -1, -1):
suffix[i] = suffix[i + 1] + piles[i]
@lru_cache(None)
def best(i: int, m: int) -> int:
"""Most stones the player to move can get from piles[i:] with the current M = m."""
if i + 2 * m >= n:
return suffix[i] # they can take everything that is left
# Take x piles; the opponent then gets best(i + x, max(m, x)) of the rest.
return suffix[i] - min(best(i + x, max(m, x)) for x in range(1, 2 * m + 1))
return best(0, 1)