Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack).
Problem: Choose the largest number of binary strings using at most m zeros and n ones in total (2-D 0/1 knapsack).
def most(strs, m, n):
dp = [[0] * (n + 1) for _ in range(m + 1)]
for s in strs:
z, o = s.count('0'), s.count('1')
for i in range(m, z - 1, -1):
for j in range(n, o - 1, -1):
dp[i][j] = max(dp[i][j], dp[i-z][j-o] + 1)
return dp[m][n]
print(most(["10", "0011", "1", "000", "110", "0"], 4, 3))What is printed?- A. 4
- B. 5
- C. 2
- D. 3
Correct answer: D. 3
Iterating the budgets backwards makes each string usable once. The best is 3 strings, e.g. '10', '1', '0' (2 zeros, 2 ones). A fourth string never fits: '000' pushes zeros to 5, '110' pushes ones to 4, '0011' pushes ones to 4. Greedily taking the shortest strings first is not safe in general; the DP checks all budgets.
More Coding Interview Problems questions
- Problem: Delete characters from two strings so they become equal, minimising the sum of ASCII codes deleted. python def cost(a, b): m, n =…
- Problem: Two players alternately take a pile from either END of a row; both play optimally. Report (first player's total) − (second…
- 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 =…