Data Structures & AlgorithmsHardAmazon · Microsoft OA
Edge case: greedy coin change versus DP when the coin system is not canonical.
Edge case: greedy coin change versus DP when the coin system is not canonical.
def greedy(coins, x):
cnt = 0
for c in sorted(coins, reverse=True):
cnt += x // c; x %= c
return cnt
def dp(coins, x):
best = [0] + [float('inf')] * x
for a in range(1, x + 1):
best[a] = min(best[a - c] + 1 for c in coins if c <= a)
return best[x]
print(greedy([1, 3, 4], 6), dp([1, 3, 4], 6), greedy([1, 5, 10, 25], 30), dp([1, 5, 10, 25], 30))What is printed?- A. 2 2 2 2
- B. 3 2 2 2
- C. 3 2 5 2
- D. 2 3 2 2
Correct answer: B. 3 2 2 2
Greedy takes 4 + 1 + 1 = 3 coins for 6, but 3 + 3 uses 2. For the canonical US coins greedy is optimal: 30 = 25 + 5 (2 coins) both ways. Greedy is safe only for canonical coin systems.
More Coding Interview Problems questions
- Problem: Count the ways to climb n stairs taking 1, 3 or 5 steps at a time (order matters). python def ways(n): dp = [1] + [0] n for i in…
- Problem: Fractional knapsack — take items (or fractions) by value/weight ratio to maximise value within capacity. python def frac(items…
- Problem: One pass of Lomuto partition (pivot = last element) as used in quicksort. python def lomuto(a): p = a[-1]; i = -1 for j in…
- Problem: Count the swaps made by bubble sort and by selection sort on the same array. python def bubble(a): a = a[:]; s = 0 for i in…
- Problem: Bottom-up heapify (max-heap) of an array; print the resulting array. python def heapify(a): n = len(a) def down(i): while True…
- Problem: Insert keys into a hash table of size 7 with open addressing and LINEAR probing, h(k) = k mod 7. python T = [None] 7 for k in…