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?- A. 0
- B. 2
- C. -3
- 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
- Problem: Prim's algorithm starts at vertex 0 on the undirected weighted graph with edges 0-1 (6), 0-3 (2), 1-2 (3), 1-3 (8), 1-4 (5), 2-4…
- Problem: A directed graph on vertices 0–5 has arcs 0→1, 1→2, 2→0, 2→3, 3→4, 4→3, 4→5. Its strongly connected components are computed. How…
- Problem: The number of spanning trees of the complete graph K4 (4 labelled vertices, every pair joined by an edge) is what value?…
- Problem: A graph on vertices 0–6 has edges 0-1, 0-2, 1-3, 2-3, 3-4, 4-5, 5-6, 4-6. Count the bridges (edges whose removal increases the…
- Problem: Maximum bipartite matching is computed for left side {A, B, C, D} and right side {1, 2, 3, 4} with allowed pairs: A–1, A–2, B–2…
- Problem: A tree has 8 nodes numbered 1–8 with edges 1-2, 1-3, 2-4, 2-5, 3-6, 3-7, 7-8. What is the size of a minimum vertex cover (a…