Data Structures & AlgorithmsVery hardProduct company OA

Problem: Two players alternately take a pile from either END of a row; both play optimally. Compute (first player's total − second player's total), and compare with a 'take the larger end' greedy.

Problem: Two players alternately take a pile from either END of a row; both play optimally. Compute (first player's total − second player's total), and compare with a 'take the larger end' greedy.
from functools import lru_cache
def stone_diff(piles):
    @lru_cache(None)
    def f(i, j):
        if i > j: return 0
        return max(piles[i] - f(i + 1, j), piles[j] - f(i, j - 1))
    return f(0, len(piles) - 1)
def greedy(piles):
    p = list(piles); turn = 0; s = [0, 0]
    while p:
        s[turn] += p.pop(0) if p[0] >= p[-1] else p.pop()
        turn ^= 1
    return s[0] - s[1]
print(stone_diff((3, 9, 1, 2)), greedy([3, 9, 1, 2]), stone_diff((4, 7, 2, 9, 5)))
What is printed?
  1. A. 7 -5 -5
  2. B. 7 -5 5
  3. C. 7 7 -5
  4. D. 5 -5 -5

Correct answer: A. 7 -5 -5

f(i, j) = best score difference for the player to move on piles i..j: take an end and subtract the opponent's best on the rest. On 3, 9, 1, 2 the first player takes 2 (not the larger 3), forcing the opponent to expose 9: final 2 + 9 vs 3 + 1 → +7. Greedy grabs 3 and loses by 5. On (4, 7, 2, 9, 5) the first player cannot avoid losing: −5. O(n²) states.

More Coding Interview Problems questions

Exams that ask this topic