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)
1import java.util.Arrays;
2
3class Solution {
4 public int stoneGameVII(int[] stones) {
5 int n = stones.length;
6 int[] prefixSum = new int[n + 1];
7 for (int i = 0; i < n; i++)
8 prefixSum[i + 1] = prefixSum[i] + stones[i];
9 int[][] dp = new int[n][n];
10
11 for (int length = 2; length <= n; length++) {
12 for (int i = 0; i <= n - length; i++) {
13 int j = i + length - 1;
14 int scoreRemoveLeft = prefixSum[j + 1] - prefixSum[i + 1];
15 int scoreRemoveRight = prefixSum[j] - prefixSum[i];
16 dp[i][j] = Math.max(scoreRemoveLeft - dp[i + 1][j], scoreRemoveRight - dp[i][j - 1]);
17 }
18 }
19 return dp[0][n - 1];
20 }
21}
22
In the Java solution, a similar logic is used where prefix sums and a 2D array are used to store intermediate results. The 2D array is iteratively filled by calculating the maximum difference in scores possible for each subarray defined by [i, j]
.
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.