1140. Stone Game II #359
-
Topics: 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 Alice and Bob take turns, with Alice starting first. Initially, On each player's turn, that player can take all the stones in the first 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:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
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:
Let's implement this solution in PHP: 1140. Stone Game II <?php
class Solution {
public function stoneGameII($piles) {
$n = count($piles);
$suffix = $piles;
$mem = array_fill(0, $n, array_fill(0, $n + 1, 0));
// Compute suffix sums
for ($i = $n - 2; $i >= 0; --$i) {
$suffix[$i] += $suffix[$i + 1];
}
return $this->stoneGameIIHelper($suffix, 0, 1, $mem);
}
private function stoneGameIIHelper($suffix, $i, $M, &$mem) {
$n = count($suffix);
// Base case: If we can take all remaining piles
if ($i + 2 * $M >= $n) {
return $suffix[$i];
}
// Check memoization
if ($mem[$i][$M] > 0) {
return $mem[$i][$M];
}
$opponent = $suffix[$i];
// Recursive case: Minimize the maximum stones opponent can take
for ($X = 1; $X <= 2 * $M; ++$X) {
if ($i + $X < $n) {
$opponent = min($opponent, $this->stoneGameIIHelper($suffix, $i + $X, max($M, $X), $mem));
}
}
// Memoize and return the result
$mem[$i][$M] = $suffix[$i] - $opponent;
return $mem[$i][$M];
}
}
// Example usage
$solution = new Solution();
$piles1 = [2, 7, 9, 4, 4];
$piles2 = [1, 2, 3, 4, 5, 100];
echo $solution->stoneGameII($piles1) . "\n"; // Output: 10
echo $solution->stoneGameII($piles2) . "\n"; // Output: 104
?> Explanation:
This approach ensures that the solution is computed efficiently, taking advantage of dynamic programming to avoid redundant calculations. |
Beta Was this translation helpful? Give feedback.
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:
dp[i][m]
represents the maximum stones Alice can collect starting from pilei
with a maximum pick limitm
.Base Case:
Recursive Case:
i
and maximum allowed pickm
, calculate the maximum stones Alice can collect by considering all possible moves (taking1
to2m
piles).Transition Function: