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 <vector>
2#include <numeric>
3#include <algorithm>
4
5class Solution {
6public:
7 int stoneGameVII(std::vector<int>& stones) {
8 int n = stones.size();
9 std::vector<int> prefixSum(n + 1, 0);
10 for (int i = 0; i < n; ++i) prefixSum[i + 1] = prefixSum[i] + stones[i];
11 std::vector<std::vector<int>> dp(n, std::vector<int>(n, 0));
12
13 for (int length = 2; length <= n; ++length) {
14 for (int i = 0; i <= n - 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] = std::max(scoreRemoveLeft - dp[i + 1][j], scoreRemoveRight - dp[i][j - 1]);
19 }
20 }
21 return dp[0][n - 1];
22 }
23};
24
The C++ solution utilizes vector containers to manage prefix sums and the DP table. Similarly, as in the C implementation, prefix sums are calculated to manage sum queries over subarrays efficiently. The 2D DP vector is then iteratively filled based on the differences between optimal scores when removing stones from either end.
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 JavaScript version embodies a recursive procedure empowered by memoization. This optimization demonstrably maximizes performance by bypassing revisits, caching previous outcomes, and thereby enhancing computational efficiency through cached results.