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)
1class Solution:
2 def stoneGameVII(self, stones: List[int]) -> int:
3 n = len(stones)
4 prefix_sum = [0] * (n + 1)
5 for i in range(n):
6 prefix_sum[i + 1] = prefix_sum[i] + stones[i]
7 dp = [[0] * n for _ in range(n)]
8
9 for length in range(2, n + 1):
10 for i in range(n - length + 1):
11 j = i + length - 1
12 score_remove_left = prefix_sum[j + 1] - prefix_sum[i + 1]
13 score_remove_right = prefix_sum[j] - prefix_sum[i]
14 dp[i][j] = max(score_remove_left - dp[i + 1][j], score_remove_right - dp[i][j - 1])
15
16 return dp[0][n - 1]
17
The Python implementation uses lists to store prefix sums and the DP table. This allows the calculation of maximum score differences in each player’s favor using pre-stored sums for any subarray, leading to an efficient solution.
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 Python solution uses recursive depth-first search combined with a dictionary for memoization to optimize state explorations. Each game state leads to further recursion unless already encountered, in which case stored results are used, thereby shortening decision times.