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)
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#include <stdio.h>
2#include <string.h>
3
4int max(int a, int b) {
5 return (a > b) ? a : b;
6}
7
8int dfs(int* stones, int left, int right, int sum, int** memo) {
9 if (left == right) return 0;
10 if (memo[left][right] != -1) return memo[left][right];
11 int removeLeft = sum - stones[left] - dfs(stones, left + 1, right, sum - stones[left], memo);
12 int removeRight = sum - stones[right] - dfs(stones, left, right - 1, sum - stones[right], memo);
13 memo[left][right] = max(removeLeft, removeRight);
14 return memo[left][right];
15}
16
17int stoneGameVII(int* stones, int stonesSize) {
18 int sum = 0;
19 for (int i = 0; i < stonesSize; i++)
20 sum += stones[i];
21 int** memo = (int**) malloc(stonesSize * sizeof(int*));
22 for (int i = 0; i < stonesSize; i++)
23 memo[i] = (int*) malloc(stonesSize * sizeof(int));
24 for (int i = 0; i < stonesSize; i++)
25 for (int j = 0; j < stonesSize; j++)
26 memo[i][j] = -1;
27 return dfs(stones, 0, stonesSize - 1, sum, memo);
28}
29
This C function uses recursion and memoization to track possible score differences by evaluating potential moves recursively. Recursive calls are cached with memoization to avoid recalculating results, reducing time spent on previously solved sub-problems.