Data Structures & AlgorithmsVery hardGoldman Sachs OA · LeetCode medium-hard

Problem: Two players alternately take a pile from either END of a row; both play optimally. Report (first player's total) − (second player's total).

Problem: Two players alternately take a pile from either END of a row; both play optimally. Report (first player's total) − (second player's total).
def diff(p):
    n = len(p); dp = p[:]
    for L in range(2, n + 1):
        for i in range(n - L + 1):
            j = i + L - 1
            dp[i] = max(p[i] - dp[i+1], p[j] - dp[i])
    return dp[0]
print(diff([4, 1, 8, 3, 2]))
What is printed?
  1. A. 6
  2. B. -4
  3. C. -2
  4. D. 0

Correct answer: C. -2

dp[i][j] = best margin for the player to move on p[i..j] = max(p[i] − dp[i+1][j], p[j] − dp[i][j−1]); the 1-D array is updated in place by increasing length. Here the first player cannot win: the total is 18 and best play leaves 8 against 10, a margin of -2. Greedy 'take the larger end' is not optimal in general, so the interval DP is needed.

More Coding Interview Problems questions

Exams that ask this topic