Data Structures & AlgorithmsVery hardICPC regional · game DP

Problem: A stone game: piles [5, 3, 4, 5] lie in a row, and players alternately take a pile from either end. The first player wants to maximise the total of the piles they take. Let dp[i][j] be the best score difference on [i, j]. Run the code and print dp[0][3] (first player minus second player).

Problem: A stone game: piles [5, 3, 4, 5] lie in a row, and players alternately take a pile from either end. The first player wants to maximise the total of the piles they take. Let dp[i][j] be the best score difference on [i, j]. Run the code and print dp[0][3] (first player minus second player).
a = [5, 3, 4, 5]
n = len(a)
dp = [[0] * n for _ in range(n)]
for i in range(n):
    dp[i][i] = a[i]
for L in range(2, n + 1):
    for i in range(n - L + 1):
        j = i + L - 1
        dp[i][j] = max(a[i] - dp[i + 1][j], a[j] - dp[i][j - 1])
print(dp[0][n - 1])
What is printed?
  1. A. 0
  2. B. 2
  3. C. -3
  4. D. 1

Correct answer: D. 1

The first player can secure a difference of 1 under optimal play, for a total of 9 against 8. The DP uses the sign flip: after taking one end, the opponent's difference on the rest is subtracted.

More Coding Interview Problems questions

Exams that ask this topic