#1872

Stone Game VIII

Hard
ArrayMathDynamic ProgrammingPrefix SumGame TheoryDynamic ProgrammingPrefix Sum
LeetCode ↗

Approaches

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

Intuition

Time O(n)Space O(1)

The optimal solution leverages dynamic programming and prefix sums to compute the maximum score difference in linear time. We can maintain a running total of the scores and use it to calculate the best possible outcome for Alice and Bob.

⚙️

Algorithm

3 steps
  1. 1Step 1: Calculate the prefix sums for the stones array.
  2. 2Step 2: Initialize a variable to keep track of the maximum score difference.
  3. 3Step 3: Iterate through the stones array, updating the maximum score difference based on the prefix sums.
solution.py8 lines
1def stoneGameVIII(stones):
2    n = len(stones)
3    for i in range(1, n):
4        stones[i] += stones[i - 1]
5    max_diff = stones[0]
6    for i in range(1, n - 1):
7        max_diff = max(max_diff, stones[i])
8    return max_diff

Complexity note: The time complexity is O(n) because we only make a single pass through the stones array to compute the prefix sums and another pass to find the maximum score difference.

  • 1The game is about strategic removal of stones to maximize score differences.
  • 2Prefix sums help in calculating scores efficiently.

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