Data Structures & AlgorithmsEasyProduct Company SDE · Amazon/Microsoft-style OA
Problem: Find the fewest coins that make an amount (−1 if impossible).
Problem: Find the fewest coins that make an amount (−1 if impossible).
def coins(cs, amt):
INF = float('inf'); dp = [0] + [INF] * amt
for a in range(1, amt + 1):
for c in cs:
if c <= a and dp[a - c] + 1 < dp[a]:
dp[a] = dp[a - c] + 1
return dp[amt] if dp[amt] != INF else -1
print(coins([1, 5, 6, 9], 11), coins([2], 3), coins([3, 7], 0))What is printed?- A. 3 -1 0
- B. 2 -1 1
- C. 2 -1 0
- D. 2 0 0
Correct answer: C. 2 -1 0
dp[a] = 1 + min dp[a − c]. 11 = 5 + 6 (2 coins), while greedy 9 + 1 + 1 uses 3. Odd 3 with coin 2 is impossible → −1. Amount 0 needs 0 coins. O(amount × coins).
More Coding Interview Problems questions
- Problem: Count the number of ways to make an amount from unlimited coins, where order does not matter. python def ways(cs, amt): dp = [1]…
- Problem: 0/1 knapsack with a 1-D array. The candidate below loops capacity upwards. python def wrong(w, v, W): dp = [0] (W + 1) for i in…
- Problem: 0/1 knapsack – maximise value within capacity W. cpp int knap(vector<int> w, vector<int> v, int W) { vector<int> dp(W + 1, 0)…
- Problem: Find the length of the longest strictly increasing subsequence of daily sales. python from bisect import bisectleft def lis(a)…
- Problem: Find the length of the longest common subsequence of two version strings. python def lcs(a, b): dp = [[0] (len(b) + 1) for in…
- Problem: Find the minimum number of insert, delete or replace operations to convert one word to another (edit distance). python def…