Data Structures & AlgorithmsHardGoldman Sachs OA · LeetCode medium-hard

Problem: Smash stones pairwise (x ≤ y leaves y − x) until at most one remains; minimise the final weight. Equivalent to splitting into two groups with the smallest difference (subset-sum DP).

Problem: Smash stones pairwise (x ≤ y leaves y − x) until at most one remains; minimise the final weight. Equivalent to splitting into two groups with the smallest difference (subset-sum DP).
def last(st):
    total = sum(st); can = {0}
    for s in st: can |= {c + s for c in can}
    return min(abs(total - 2 * c) for c in can)
print(last([31, 26, 33, 21, 40]), last([3, 9, 7, 3]))
What is printed?
  1. A. 1 2
  2. B. 9 0
  3. C. 5 2
  4. D. 5 4

Correct answer: C. 5 2

Any smashing order corresponds to assigning + and − signs to stones. First set: total 151; the best subset sum below 75.5 is 73 (40 + 33), giving 151 − 146 = 5. Second: total 22, but no subset sums to 11, so the best split is 12 (9 + 3) vs 10 (7 + 3): difference 2.

More Coding Interview Problems questions

Exams that ask this topic