MediumArrayMathDynamic ProgrammingGame Theory

1 approach, code in every language

Problem description

Alice and Bob play a game with a row of stones, where the value of each stone is given in the array stones. Alice goes first and the players alternate turns. On a turn, a player removes either the leftmost or the rightmost remaining stone and earns points equal to the sum of the values of all stones that are still on the row after the removal.

Both players play optimally, and each one wants to maximize the difference between their own total score and the opponent's total score. Return the difference between Alice's score and Bob's score at the end of the game assuming both play optimally.

Example 1

Input: stones = [5,3,1,4,2]

Output: 6

With optimal play the players trim the row from both ends so that Alice keeps a lead of exactly 6 points over Bob by always choosing the end that maximizes her own margin.

Example 2

Input: stones = [7,90,5,1,100,10,10,2]

Output: 122

Each removal scores the sum of what remains, so early moves are worth the most. Optimal alternating choices leave Alice ahead by 122 points.

Constraints

  • n == stones.length
  • 2 <= n <= 1000
  • 1 <= stones[i] <= 1000

After the pattern

Now solve one you haven't seen.

Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.

1,194 problems · 15,062 graded tests · free