Taro Logo

Stone Game VIII

#6 Most AskedHard
0 views
Topics:
ArraysDynamic Programming

Alice and Bob take turns playing a game, with Alice starting first.

There are n stones arranged in a row. On each player's turn, while the number of stones is more than one, they will do the following:

  1. Choose an integer x > 1, and remove the leftmost x stones from the row.
  2. Add the sum of the removed stones' values to the player's score.
  3. Place a new stone, whose value is equal to that sum, on the left side of the row.

The game stops when only one stone is left in the row.

The score difference between Alice and Bob is (Alice's score - Bob's score). Alice's goal is to maximize the score difference, and Bob's goal is the minimize the score difference.

Given an integer array stones of length n where stones[i] represents the value of the ith stone from the left, return the score difference between Alice and Bob if they both play optimally.

Example 1:

Input: stones = [-1,2,-3,4,-5]
Output: 5
Explanation:
- Alice removes the first 4 stones, adds (-1) + 2 + (-3) + 4 = 2 to her score, and places a stone of
  value 2 on the left. stones = [2,-5].
- Bob removes the first 2 stones, adds 2 + (-5) = -3 to his score, and places a stone of value -3 on
  the left. stones = [-3].
The difference between their scores is 2 - (-3) = 5.

Example 2:

Input: stones = [7,-6,5,10,5,-2,-6]
Output: 13
Explanation:
- Alice removes all stones, adds 7 + (-6) + 5 + 10 + 5 + (-2) + (-6) = 13 to her score, and places a
  stone of value 13 on the left. stones = [13].
The difference between their scores is 13 - 0 = 13.

Example 3:

Input: stones = [-10,-12]
Output: -22
Explanation:
- Alice can only make one move, which is to remove both stones. She adds (-10) + (-12) = -22 to her
  score and places a stone of value -22 on the left. stones = [-22].
The difference between their scores is (-22) - 0 = -22.

Constraints:

  • n == stones.length
  • 2 <= n <= 105
  • -104 <= stones[i] <= 104

Solution


Clarifying Questions

When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:

  1. What are the constraints on the length of the stones array, and can the stone values be negative?
  2. What is the minimum number of stones in the input array, and how should we handle the edge case where there are fewer than two stones?
  3. Does 'removing stones from the left' mean we must always remove a prefix of length $k$ (where $2 \le k \le n$) and replace it with the single sum of those removed stones?
  4. Does the phrase 'maximum score difference the first player can achieve' mean Player 1's score minus Player 2's score, and do both players adopt a minimax strategy?
  5. Is the return value expected to be a single integer representing the final score difference for the first player?

Brute Force Solution

Approach

The game allows a player to take the first x stones and replace them with their sum, which is equivalent to selecting a prefix sum at index x - 1. Each chosen prefix sum adds to the current player's score and leaves the remaining prefix sums available for the other player. By utilizing dynamic programming backwards from the last possible choice, we can compute the maximum score difference each player can guarantee.

Here's how the algorithm would work step-by-step:

  1. Calculate the prefix sum array for the given stone values.
  2. Recognize that choosing the last stone yields a score difference equal to the total sum of all stones.
  3. Iterate backwards from the second-to-last prefix sum down to index 1.
  4. At each index, update the best score difference by taking the maximum between skipping the current choice and choosing the current prefix sum minus the opponent's best outcome.
  5. Return the resulting score difference obtained after considering all valid initial choices.

Code Implementation

def stone_game_viii(stones: list[int]) -> int:
    # Compute the prefix sums of the stone values
    prefix_sums = [0] * len(stones)
    prefix_sums[0] = stones[0]
    for index in range(1, len(stones)):
        prefix_sums[index] = prefix_sums[index - 1] + stones[index]
    
    # If the game must end at the last element, the score difference is its prefix sum
    best_difference = prefix_sums[-1]
    
    # Work backwards to find the optimal decision at each step
    for index in range(len(stones) - 2, 0, -1):
        best_difference = max(best_difference, prefix_sums[index] - best_difference)
        
    return best_difference

Big(O) Analysis

Time Complexity
O(n) – Computing the prefix sums takes linear time, and the backward pass over the array also runs in linear time with respect to the number of stones.
Space Complexity
O(n) – The algorithm allocates an array of size n to store the prefix sums of the stones.

Optimal Solution

Approach

Every legal move takes a prefix of the remaining stones, adds that prefix sum to the current player's score, and leaves the opponent to play from there. The best score difference is the prefix sum of a move minus the best difference the opponent can force afterward. One backward pass finds that value.

Here's how the algorithm would work step-by-step:

  1. Build the running sum of the stones from left to right. A move that consumes stones up through a position is worth exactly that running sum.
  2. Taking every remaining stone is always legal, so start from the sum of the whole row.
  3. Walk backward from the second-to-last stone toward the second stone.
  4. At each stone, the player to move can take the running sum there and leave the opponent with the best difference already computed to the right.
  5. The difference for that choice is the running sum minus the opponent's difference.
  6. Keep the larger of that choice and the best difference already known. The value left at the end is the difference the first player can force.

Code Implementation

def stone_game_viii(stones):
    prefix_sums = []
    running_sum = 0
    for stone in stones:
        running_sum += stone
        prefix_sums.append(running_sum)
    best_difference = prefix_sums[-1]
    for index in range(len(stones) - 2, 0, -1):
        best_difference = max(best_difference, prefix_sums[index] - best_difference)
    return best_difference

Big(O) Analysis

Time Complexity
O(n) – The prefix sums are built in one pass, and the best difference is chosen in a second pass.
Space Complexity
O(n) – The prefix sums are stored for every stone.

Edge Cases

Input array with exactly two elements
How to Handle:
The game must stop when one stone remains, so the only valid move is taking both stones immediately, resulting in the sum of the whole array.
Array containing entirely negative numbers
How to Handle:
Prefix sums will become increasingly negative, but the dynamic programming state transitions will still correctly maximize the score difference.
Very large arrays approaching the maximum length constraints
How to Handle:
An O(N) suffix maximum approach using prefix sums ensures the solution scales efficiently without exceeding time or memory limits.
Extreme values of stone weights causing integer overflow
How to Handle:
Using 64-bit integer types for the prefix sums and score calculations prevents arithmetic overflow during summation.
Input array with all zeros
How to Handle:
Prefix sums remain zero throughout, and optimal play will result in a final score difference of zero.
Alternating large positive and negative numbers
How to Handle:
The suffix maximum logic correctly evaluates whether to make a move now or skip ahead to a more profitable future state.
0/257 completed