Sponsored
Sponsored
This approach uses dynamic programming along with pre-computed prefix sums to efficiently calculate the score differences.
We maintain a 2D DP table where dp[i][j]
represents the maximum score difference the current player can achieve over the other player from index i
to j
. The prefix sums help in computing the sum of the stones between any two indices in constant time, which we require to decide which stone to remove to maximize the score difference.
Time Complexity: O(n^2)
Space Complexity: O(n^2)
1#include <stdio.h>
2#include <string.h>
3
4int stoneGameVII(int* stones, int stonesSize) {
5 int prefixSum[stonesSize + 1];
6 prefixSum[0] = 0;
7 for (int i = 0; i < stonesSize; i++)
8 prefixSum[i + 1] = prefixSum[i] + stones[i];
9
10 int dp[stonesSize][stonesSize];
11 memset(dp, 0, sizeof(dp));
12
13 for (int length = 2; length <= stonesSize; length++) {
14 for (int i = 0; i <= stonesSize - length; i++) {
15 int j = i + length - 1;
16 int scoreRemoveLeft = prefixSum[j + 1] - prefixSum[i + 1];
17 int scoreRemoveRight = prefixSum[j] - prefixSum[i];
18 dp[i][j] = fmax(scoreRemoveLeft - dp[i + 1][j], scoreRemoveRight - dp[i][j - 1]);
19 }
20 }
21 return dp[0][stonesSize - 1];
22}
23
In this C implementation, we start by computing the prefix sums to get the sum of elements between any two indices quickly. We then fill a 2D DP table, where each cell dp[i][j]
holds the maximum score difference the current player can secure from stones in the subarray stones[i...j]
. The scores for each move are calculated using the prefix sums, and we use the results to populate the DP table iteratively.
This approach leverages recursive backtracking with memoization to explore all possible game states and store previously computed results to prevent redundant calculations. Unlike the iterative DP approach, this recursive strategy keeps track of outcomes by diving directly into decision trees, thus exposing base-level game decisions before accumulating overall results with stored solutions.
Time Complexity: O(n^2)
(with memoization)
Space Complexity: O(n^2)
1
The Java method involves creating a recursive DFS strategy coupled with memoization. This method evaluates each possibility by recursively transitioning between states and then memoizing the results for each state, which are evaluated when referred to from future calls.