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. Initially, M = 1.
On each player’s turn, that player can take all the stones in the firstX remaining piles, where 1 <= X <= 2M. Then, we set M = max(M, X).
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.
Input: piles =[2,7,9,4,4]Output: 10Explanation: 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 piles in total. If Alice takes two piles at the beginning, then Bob can take all three piles left. In thiscase, Alice get 2+7=9 piles in total. So we return10 since it's larger.
Method 1 - By minimizing the stones returned by Bob#
The game involves Alice and Bob playing optimally to collect as many stones as possible from a row of piles. Alice always plays first, and the players take turns. The key constraints are:
Each player can take any number of piles between 1 and 2M, where M is initially set to 1 and adjusts based on the moves.
The goal is to maximize the number of stones collected by Alice.
Prefix Sums:
We use prefixSums to quickly calculate the sum of stones from any subarray.
prefixSums[i] stores the total number of stones from the start up to the i-th pile.
Memoization Table:
memo[i][M] stores the maximum number of stones Alice can collect starting from index i with the parameter M.
This avoids recalculating results for the same state multiple times.
Recursive Function:
The helper function findMaxStones handles the game logic recursively.
It ensures that both players play optimally, and calculates Alice’s maximum possible stones.
This is how recursion will work:
The goal is to maximize Alice’s collected stones. For each possible number of piles X Alice can take (from 1 to 2 * M):
Calculate the total stones Alice can collect by summing the stones from index i to i + X - 1.
Recursively compute the result for the remaining piles starting from index i + X, and adjust M to max(M, X).
Deduct the maximum stones Bob can collect in his turn from the total stones Alice can collect.