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?- A. 6
- B. -4
- C. -2
- 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
- Problem: Count the combinations (multisets) of candidates that sum to the target; each candidate may be used any number of times. python…
- Problem: AND of every integer in the range [lo, hi]. python def rangeand(lo, hi): shift = 0 while lo != hi: lo >>= 1; hi >>= 1; shift += 1…
- Problem: Ugly numbers have no prime factors other than 2, 3 and 5. Generate them in order with three pointers. python def ugly(n): u =…
- Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses. python def frac(n, d): q, r = divmod(n, d); s =…
- Generating all permutations of n distinct items with backtracking and copying each complete permutation into the result list costs how…
- A disjoint-set forest uses path compression but NO union by rank/size. What is its amortised cost per operation over m operations on n…