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?- A. 1 2
- B. 9 0
- C. 5 2
- 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
- Problem: You may swap a[i] with b[i] at any indices. Find the minimum swaps making BOTH arrays strictly increasing (DP with 'swapped at i'…
- Problem: Remove every interval that is covered by another interval ([a, b] is covered by [c, d] if c ≤ a and b ≤ d); count those that…
- Problem: Delete the fewest characters from a string of a's and b's so that no 'b' comes before an 'a'. python def mindel(s): bseen = dels…
- Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to…
- Problem: Validate a byte sequence as UTF-8 (a 1-byte char starts 0xxxxxxx; an n-byte char starts with n 1s and a 0, followed by n − 1…
- Problem: The infinite string 123456789101112… is indexed from 1. Find the n-th digit by skipping whole blocks of 1-digit, 2-digit, ……