Stone Game VII

This problem can be solved using dynamic programming. We can maintain a 2D table dp, where dp[i][j] represents the maximum difference in score that Alice can achieve by playing optimally on the subarray stones[i:j+1].

Since the score depends on the sum of the remaining stones, we can create a prefix sum array to easily calculate the sum of any subarray.

Here’s the Python code:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution:
    def stoneGameVII(self, stones: List[int]) -> int:
        n = len(stones)

        # Calculate the prefix sum array
        prefix_sum = [0] * (n + 1)
        for i in range(n):
            prefix_sum[i + 1] = prefix_sum[i] + stones[i]

        # Initialize the dp table
        dp = [[0] * n for _ in range(n)]

        # Iterate through all possible lengths of the subarray
        for length in range(2, n + 1):
            for i in range(n - length + 1):
                j = i + length - 1

                # Calculate the score if we remove the leftmost or rightmost stone
                remove_left = prefix_sum[j + 1] - prefix_sum[i + 1]
                remove_right = prefix_sum[j] - prefix_sum[i]

                # Store the maximum difference in the dp table
                dp[i][j] = max(remove_left - dp[i + 1][j], remove_right - dp[i][j - 1])

        return dp[0][n - 1]

Explanation:

  • We start by calculating the prefix sum array to efficiently compute the sum of any subarray.
  • We initialize the dp table with dimensions n x n and fill it with zeros.
  • We iterate through all possible lengths of the subarray, from 2 to n, and consider all possible starting points i for that length.
  • For each subarray stones[i:j+1], we calculate the score for removing the leftmost stone (remove_left) and the score for removing the rightmost stone (remove_right).
  • We store the maximum difference between these two options in the dp table.
  • Finally, the result is stored in dp[0][n - 1], which represents the maximum difference for the entire array.

The time complexity of this solution is (O(n^2)), and the space complexity is also (O(n^2)), where (n) is the length of the stones array.