Home >Backend Development >PHP Tutorial >Stone Game II
1140. Stone Game II
Difficulty: Medium
Topics: Array, Math, Dynamic Programming, Prefix Sum, Game Theory
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 first X 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.
Example 1:
Example 2:
Constraints:
Hint:
Solution:
We need to use dynamic programming to find the maximum number of stones Alice can get if both players play optimally. Here's a step-by-step approach to develop the solution:
Define the State and Transition:
Base Case:
Recursive Case:
Transition Function:
Let's implement this solution in PHP: 1140. Stone Game II
stoneGameII($piles1) . "\n"; // Output: 10 echo $solution->stoneGameII($piles2) . "\n"; // Output: 104 ?>Explanation:
- Prefix Sum Calculation: This helps in quickly calculating the sum of stones from any pile i to j.
- DP Array Initialization: dp[i][m] holds the maximum stones Alice can get starting from pile i with a maximum pick limit of m.
- Dynamic Programming Transition: For each pile and m, compute the maximum stones Alice can collect by iterating over possible pile counts she can take and updating the DP array accordingly.
This approach ensures that the solution is computed efficiently, taking advantage of dynamic programming to avoid redundant calculations.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
The above is the detailed content of Stone Game II. For more information, please follow other related articles on the PHP Chinese website!