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?- A. 7 -5 -5
- B. 7 -5 5
- C. 7 7 -5
- 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
- Problem: Maximum sum of a non-empty contiguous subarray where you may delete at most one element (the result must stay non-empty). Track…
- Problem: Assign 4 workers to 4 jobs (one each) minimising total cost with a bitmask DP over the set of jobs already taken; compare with…
- Problem: Convert Roman numerals to integers: a symbol smaller than the one after it is subtracted. python def roman(s): v = {"I": 1, "V"…
- Problem: Is b a rotation of a? Check equal lengths and whether b occurs in a + a. python def isrot(a, b): return len(a) == len(b) and b in…
- Problem: String t is string s shuffled with one extra letter added. Find the extra letter by XOR-ing all character codes. python from…
- Problem: Look-and-say: read the previous term aloud in runs ("1" → "11" → "21" …). python def say(s): out, i = [], 0 while i < len(s): j =…