#1690

Stone Game VII

Medium
ArrayMathDynamic ProgrammingGame TheoryDynamic ProgrammingGame Theory
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n²)
Space
O(1)
O(n²)
💡

Intuition

Time O(n²)Space O(n²)

The optimal solution uses dynamic programming to store previously computed results, avoiding redundant calculations. This allows us to efficiently determine the maximum score difference by considering the optimal choices of both players.

⚙️

Algorithm

3 steps
  1. 1Step 1: Create a DP table where dp[i][j] represents the maximum score difference when considering stones from index i to j.
  2. 2Step 2: Initialize the DP table for the base cases where only one stone is left.
  3. 3Step 3: Fill the DP table iteratively based on the choices of removing stones from either end.
solution.py9 lines
1def stoneGameVII(stones):
2    n = len(stones)
3    dp = [[0] * n for _ in range(n)]
4    total = sum(stones)
5    for length in range(2, n + 1):
6        for i in range(n - length + 1):
7            j = i + length - 1
8            dp[i][j] = max(total - stones[i] - dp[i + 1][j], total - stones[j] - dp[i][j - 1])
9    return dp[0][n - 1]

Complexity note: The time complexity is O(n²) due to the nested loops filling the DP table, while the space complexity is also O(n²) for storing the results in the DP table.

  • 1Both players will always play optimally, making the game a perfect information game.
  • 2The total score of remaining stones is crucial for determining the best moves.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.