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:
2 + 4 + 4 = 10
stones in total.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 <= 100
1 <= piles[i] <= 104
This problem involves a two-player game with piles of stones. The players take turns removing stones, and the goal is to maximize the number of stones collected. The key to solving this efficiently is recognizing the optimal strategy involves dynamic programming.
Understanding the Game:
Each turn, a player can take 1 to 2M stones from the beginning of the remaining piles, where M is the maximum number of piles taken in any previous turn. M starts at 1. The game ends when all stones are taken.
Approach: Dynamic Programming with Memoization
The most efficient approach uses dynamic programming with memoization to avoid redundant calculations. We'll create a recursive function dfs(i, m)
that represents the maximum number of stones the current player can get, starting from index i
in the piles
array and with the current maximum number of piles taken (M) being m
.
1. Base Case:
If m * 2 >= n - i
, it means there are few enough remaining piles that the current player can take them all. In this case, the current player takes all remaining stones (s[n] - s[i]
, where s
is the prefix sum array).
2. Recursive Step:
Otherwise, the current player can choose to take x
piles (1 ≤ x ≤ 2m). For each choice of x
, the opponent will get the maximum number of stones they can obtain from the remaining piles, which is recursively calculated as dfs(i + x, max(m, x))
. The current player aims to maximize their score, so they choose the x
that minimizes the opponent's score, leading to the maximum score for themselves.
3. Memoization:
To avoid recomputing the same dfs(i, m)
values repeatedly, we use memoization (a cache) to store previously computed results.
4. Prefix Sum:
We use a prefix sum array s
to efficiently calculate the sum of stones in a range. s[i]
stores the sum of the first i
piles. The sum of stones from index i
to j
is then s[j+1] - s[i]
.
Time and Space Complexity:
dfs
has three nested loops implicitly: the outer loop is the recursion depth (n), the inner loop iterates through possible values of x (2m), and inside the min function is a nested loop (implicit in the recursion).dfs(i,m)
for all possible values of i
and m
.Code Implementation (Python):
from functools import cache
from itertools import accumulate
import math
class Solution:
def stoneGameII(self, piles: List[int]) -> int:
n = len(piles)
s = list(accumulate(piles, initial=0)) # Prefix sum array
@cache
def dfs(i: int, m: int = 1) -> int:
if m * 2 >= n - i: # Base case: Take all remaining piles
return s[n] - s[i]
min_opponent_score = float('inf')
for x in range(1, min(2 * m + 1, n - i)): # Optimization: Limit x to available piles
min_opponent_score = min(min_opponent_score, dfs(i + x, max(m, x)))
return s[n] - s[i] - min_opponent_score # Maximize current player's score
return dfs(0)
Other Languages:
The approach and logic remain the same across different programming languages. The key differences lie in syntax and the way memoization is implemented (using dictionaries/maps in Python/Java/C++, or similar data structures in other languages). The Python code above is already efficient and well-structured. Adapting it to other languages involves straightforward translation. The earlier response already contains code samples in several languages, you can refer to those.